Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delay the Execution of a Javascript Function After a Live Keyup event is called?

Hey programmers, I have removed everything from my function below to just target exactly what I need help with...

After the keyup event is called, the reloadContent function will make an ajax call to gather new data from a database.

Only problem is, my servers are overloading because there is no delay from the keyup events, after every keyup the function is called.

I need a way to delay, say 1 second, before the reloadContent function is called. This way it will not run 4 times (when the user types in j o h n) but only 1 time after the user types (john), assuming they can type more than 1 character/sec.

$('#searchinput').live('keyup',function() {

        reloadContent(); //execute load function

});

Any advice is appreciated

like image 244
TaylorMac Avatar asked May 29 '11 06:05

TaylorMac


People also ask

How do I delay a Keyup event?

There are two ways to achieve the same: Approach 1: Using the keypress(), fadeIn(), delay() and fadeOut() methods in the jQuery library and clearTimeout() and setTimeout() methods in native JavaScript.

How can you delay the execution of the function?

To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.

What is Keyup event in JavaScript?

The keyup event occurs when a keyboard key is released. The keyup() method triggers the keyup event, or attaches a function to run when a keyup event occurs. Tip: Use the event. which property to return which key was pressed.


2 Answers

You can set a timeout in your keyup handler and use jQuery's data() facility to associate its id with the element. That way, if the keyup event is triggered again before the delay runs out, you can clear the existing timeout and schedule a new one:

$("#searchinput").live("keyup", function() {
    var $this = $(this);
    var timerId = $this.data("timerId");
    if (timerId) {
        window.clearTimeout(timerId);
    }
    $this.data("timerId", window.setTimeout(reloadContent, 1000));
});
like image 97
Frédéric Hamidi Avatar answered Nov 15 '22 04:11

Frédéric Hamidi


$('#searchinput').live('keyup',function() {
    window.setTimeout(function(){
        reloadContent(); //execute load function
    },1000);
});

This will make a delay, but I think you need not only delay to make what you want.

like image 26
Larry Cinnabar Avatar answered Nov 15 '22 06:11

Larry Cinnabar