Implementing Delay Between Ajax Calls

25 / Feb / 2010 by Imran Mir 0 comments

Implementing search functionality on the keyup event using ajax has one pitfall. It can bombard our server with unnecessary ajax calls. So it becomes imperative for us to introduce some delay between the ajax calls. One way to implement it will be to make an ajax call after some delay(say 500 ms) after the first character has been typed in the text box. But,a better solution will be to make the ajax call after 500ms, after the last character has been typed. The idea is to clear the timer on each key-up event till the user types in the last charecter.
This solution can be implemented as given below:


 var alertTimerId = 0;
function activateTimer(objId) {
    clearTimeout(alertTimerId);
    alertTimerId = setTimeout('sendData("' + objId + '")', 500);
  }
  function sendData(objId) {
    ajax call 
  }

Here, the instance or identifier of the time out call is captured in a variable and then this identifier is passed to clearTimeout function to clear the timer.
Another problem associated with ajax search on keyup event is that if we are using tab button to navigate between different search fields, unnecessary ajax calls are shooted. To prevent this we can modify our activateTimer function like this :

function activateTimer(objId, event) {
    if (event.which == 9) {
    }
    else {
      clearTimeout(alertTimerId);
      alertTimerId = setTimeout('sendData("' + objId + '")', 500);
    }
  }

Event argument can be passed as parameter like this :

  

Hope you find this useful.
Imran Mir
imran@intelligrape.com

Tag -

FOUND THIS USEFUL? SHARE IT

Leave a comment -