setInterval
and setTimeout
can be extremely useful and important, but using either of them in complex ways can be a confusing ordeal. In this tutorial, I'm going to try and show the range of possibilities, from the very simple, to the complex, to the 'why oh why is it working like this!?'.So lets start out with the extremely simple - what do the
setInterval
and setTimeout
functions do?They are both functions attached to the
window
object of a web page, and they allow, in a very crude manner, a sort of 'thread-like' control.The
setTimeout
call lets you tell the browser to execute a javascript call after a certain time has passed. It takes two arguments - what to execute, and how long to wait (in milliseconds). Here is an example of a very simple setTimeout
call:setTimeout("alert('hi!');", 500);
alert('hi!');
after 500 milliseconds has passed.The
setInterval
call has similar arguments, but instead of just executing the given code once, it executes it over and over again, using the second argument as the amount of time to wait between executions. Here is a simple example of a setInterval
call:setInterval("alert('hi!');", 500);
alert('hi');
every 500 milliseconds from now until the the page it is loaded on is closed.But if that was all you could do with these two functions, it wouldn't be very interesting, now, would it? Fortunately, that is only the tip of the iceberg.
Both of these functions return an integer id when they are called - which in and of itself is not very useful. But what these ids allow you to do is clear an interval/timeout call if you don't want it anymore. There are two companion funtions called
clearTimeout
and clearInterval
which you can pass these ids to - and they will clear the timeout/interval associated with the id. This especially useful for setInterval
, because it is probably rare that you want something on your page executing every X milliseconds for the entire time the user has the page open.Using the functions is very simple, you can just call them like the following:
var timeoutID = setTimeout("alert('hi!');", 500);
var intervalID = setInterval("alert('hi!');", 500);
clearTimeout(timeoutID);
clearInterval(intervalID);
Ref: http://www.switchonthecode.com/tutorials/javascript-tutorial-using-setinterval-and-settimeout
var intervalID = setInterval("alert('hi!');", 500);
clearTimeout(timeoutID);
clearInterval(intervalID);
Ref: http://www.switchonthecode.com/tutorials/javascript-tutorial-using-setinterval-and-settimeout
No comments:
Post a Comment