JavaScript: add a delay to the keyup() event

luca 17/06/2013 0

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) {
		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);

delay(myKeyUpFunction, 250);

Leave A Response »

This website uses cookies to ensure you get the best experience on our website maggiori informazioni

Questo sito utilizza i cookie per fonire la migliore esperienza di navigazione possibile. Continuando a utilizzare questo sito senza modificare le impostazioni dei cookie o clicchi su "Accetta" permetti al loro utilizzo.