Handy Javascript Functions: setTimeout()/clearTimeout()

So the other day I was working on a simple Ajax filter text box. As the user entered text, the table below it would filter based on the entries in the text box. It was simple enough, I was using the onKeyUp event in javascript so that each time the user released the key, the Ajax request was made.

Some of you will see the problem with this already. If the user quickly types in 5, 8, 10, 12 characters, the browser would make that many Ajax calls. And it got even worse if the user hit Backspace several times to clear the field.

I needed a way to tell the browser to wait a second after each onKeyUp before it made the Ajax call, and if another event fired, to cancel the previous one.

Enter setTimeOut().

I have seen this Javascript function mentioned before, but I have never really looked into what it does. setTimeout() takes 2 arguments, a Javascript Expression and an integer representing the number of milliseconds the function should wait before the expression is executed.

So that solved the first half of my problem, I was able to get the browser to wait for a second before executing the call. So far my simple tool looked like this:


<script type="text/javascript">
function setTimer() {
setTimeout("makeCall()", 1000);
}

function makeCall() {
Ajax call code was here
}

</script>

<input type="text" name="filter" id="filter" onkeyup="setTimer()" />

This was great. Now I just need a way to cancel the timer if a new key up event occurred. Then I came across clearTimeout(). It's like they were make for each other.

One of the cool things about setTimeout() is that it returns a unique id for that timer, so you can pass that unique id to clearTimeout() to cancel it. So I was able to set a default time to 0 when the page loaded, then on each key up event I called the setTimer() function. That function would clear the old timer and make a new one, then wait a second for another request to come in, if it did, it would cancel the previous and wait again, if no new request came in, it would make a single Ajax call based on the value of the target field.


<script type="text/javascript">
var currentTimer = 0;

function setTimer() {
clearTimeout(currentTimer);

currentTimer = setTimeout("makeCall()", 1000);

}

function makeCall() {
Ajax call code was here
}

</script>

<input type="text" name="filter" id="filter" onkeyup="setTimer()" />

Related Blog Entries

Comments
Bradley Moore's Gravatar That's quite handy.
# Posted By Bradley Moore | 6/25/08 7:08 AM
mitja's Gravatar Indeed. The only issue I have a problem with is polluting the global namespace with the timer variable which becomes more noticeable as you build a larger application but for most 'DHTML' style scripts it shouldn't be much of an issue
# Posted By mitja | 5/6/09 7:31 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.9.1. Contact Blog Owner