Forum Moderators: open

Message Too Old, No Replies

Best method of doing a time delay on ajax-based search results

         

digitalv

2:32 pm on May 5, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Most of us have probably done this by now where you use an onKeyUp/onKeyDown to execute a search function which returns a few results into a DIV as users are typing their search query.

I'd like to make this a little less server-intensive, but not sure of the most efficient way to do it. Basically, rather than having the query executed EVERY TIME onKeyUp, I would like to do it based on a second of inactivity afterward.

So when the user is typing along normally nothing happens, but as soon as they STOP for one second, then the ajax event fires and shows them the results. Any ideas?

Fotiman

2:55 pm on May 5, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



You'll want to use the setTimeout and clearTimeout methods.

When the user presses a key, your event handler function will clear the timer (if it is set), then start the timer. You'll need a globally accessible variable to store the timer id. Here's a rough example:


var timerId = 0;
function keypressed() {
clearTimeout(timerId);
timerId = setTimeout(search, 1000);
}
function search() {
// Perform the AJAX search
}