JavaScript: add a delay to the keyup() event

by luca
0 comment

When you’re developing an AJAX application, you often use the onkeyup() event that is fired every time the user releases a key on the keyboard.

Let’s consider for example an autocomplete function: every time the user enters a character in a field, the application, using JavaScript, queries the server for hints:

Sometimes – to avoid calling the function too many times – it would be useful to define a waiting period; after which, if the user didn’t type a new character, the function is called.

Define in your source a new JavaScript function, delay():

var delay = (function () {
	var timer = 0;
	return function (callback, ms) {
		clearTimeout(timer);
		timer = setTimeout(callback, ms);
	};
})();

delay() gets as inputs the function to be called and the waiting period, in milliseconds.

How to use it: if you need to call the myKeyUpFunction() function if at least 250ms have passed since the last character typed in the mySearchBox field, write

$(mySearchBox).keyup(function() {
 
		delay(myKeyUpFunction, 250);
}

Related Posts

Leave a Comment

16 + fourteen =