Javascript – function to manage function timeout

Working with form validations and AJAX requests associated with the event keyup in the input fields.

Sometimes the validation requires an AJAX call (for instance to check if the typed text already exists in the DB). In order to avoid a request for each char typed, a good solution might be using set/clearTimeout.

With the aim of doing only one function to manage all the timeouts of the functions called for each field, I’ve written a general function that does that, supporting dynamically the function name.

It uses an array (member of the function) to store the timeouts of the functions called, and an eval to launch/stop the each function with the relative timeout.

function callTimeout(funcName, timeout, args) {   if (args==undefined) {args = "";}

if (timeout == undefined)  { timeout=500; }

if (this.timeOutsArray == undefined) {      this.timeOutsArray = new Array(); }

if (this.timeOutsArray[funcName] == undefined)

{      this.timeOutsArray[funcName] = 0;   }

if (this.timeOutsArray[funcName]) {       clearTimeout(this.timeOutsArray[funcName]);   }   eval("this.timeOutsArray['"+funcName+"'] = setTimeout('" + funcName + "("+args+")', "+timeout+");");}

Example of use with JQuery:



Behaviour: If the user types very quickly in the search box (id=field1), the function is not called hundreds time, but just at the end after 500ms.

Leave a Reply

Your email address will not be published. Required fields are marked *