Depending on how fast you type, onkeyup triggers multiple times

Viewed 227

I'm encountering a very strange issue with an onkeyup function. Depending how fast the person types, the function that is triggered by typing may run multiple times.

var inputFilter = document.getElementById('inputFilter');
inputFilter.onkeyup = function(e, value) {
e.preventDefault();
 value = e.target.value
   if (value.length >= 3) {
     console.log(value);
      getItems(value);
   }
};

If I type slowly, the getItems() function runs perfectly, but if I type really fast it behaves strangely. The getItems() function pulls data from a SharePoint list using Ajax(XMLHttpRequest()), and creates a table with the results. If I type slowly, the table is just fine, but if I type fast, each table row duplicates. I added to the getItems() function a body.innerHTML = '' to make sure it empties the table's body with each run of of the function:

 const table = document.getElementById('smeTable'),
 body = table.getElementsByTagName('tbody')[0];
 body.innerHTML = '';

I'm not a programmer, and probably will get many down votes for this probably silly question, but I'm puzzled by this issue. Any ideas would be appreciated. Thank you.

1 Answers

That probably happens because you are producing a lot of ajax requests in a short period of time and since the responses are async, response to the previous keyUp events might load after the response from current keyup and it might mess things up, especially if you are pulling some autocomplete results.

What I would usually do is abore previous ajax request when creating a new request. You can follow an answer from here on how to abort the previous request: Abort previous ajax request on new request

 var currentRequest = null;    

currentRequest = jQuery.ajax({
    type: 'POST',
    data: 'value=' + text,
    url: 'AJAX_URL',
    beforeSend : function()    {           
        if(currentRequest != null) {
            currentRequest.abort();
        }
    },
    success: function(data) {
        // Success
    },
    error:function(e){
      // Error
    }
});
Related