Question

I have a live search method which searches as you type in the textbox. The service it uses is taking quite a long time so I have decided to call the searching service only when a user pauses or stops typing for n seconds, say 0.5 sec. While doing it like this

j$132('#AdvanceSearch table:first input').unbind('keyup').keyup(function () {
    window.setTimeout(function () {
        LoadAdvanceSearch();
    }, 500);
});

It waits for 500msec that's fine but for every keyup it waits and then send another service call.

Is there a trick that under onkeyup it calls the method only once when the user finishes typing.

Was it helpful?

Solution

I would do something like this;

var keyTimer;

j$132('#AdvanceSearch table:first input').keyup(function () {

    if(keyTimer){
        clearTimeout(keyTimer);
    }
    keyTimer = setTimeout(function () {
        LoadAdvanceSearch();
    }, 500);

});

It will clear the timeout each time if it has not fired yet. So then it will only run if the user stops typing for half a second.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top