August 28, 2012

The setInterval() method is part of the window object that either calls a function at some specified time interval. It can also evaluate an expression. The interval is specified in milliseconds.

The setInterval() method, can for example, be used to display a timer on a page. The function called with this method will continue to run until the clearInterval() method is called.

An example of the setInterval() method is below.

<script type="text/javascript">
var
interval = window.self.setInterval(function () { ShowTime() }, 1000);
function ShowTime() {
var time = new Date().toTimeString();
document.getElementById("id1").innerHTML = time;
}</script>
<span id="id1">Date will appear here</span>

 

An example of how to stop the setInterval() using clearInterval() method is below. Note that, the ID set by setInterval() method is used within the clearInterval() method to stop the timer.

<button id="b1" onclick="window.clearInterval(interval)">Stop</button>


On the other hand, the setTimeout() method which is part of the Window object can be used to run a function or expression after a specified time. The syntax for this method is similar to setInterval() method. This function can be used, for example, to display some message to the end user after a specified period of time. The message, for example, could be a call to action for a user who has spent at 1 minute on the page, etc.

An example of the setTimeout() method works is below.

var interval2 = window.self.setTimeout(function () { ShowAfterSomeTime() }, 10000);
function ShowAfterSomeTime() {
var time = new Date().toTimeString();
document.getElementById("id2").innerHTML = time;
}

The setTimeout() method's timer can be cleared by using the clearTimeout() method. This might be useful when, for example, a message needs to be displayed after a particular time but due to user's actions, we choose not to display the message, etc.

An example of how to use the clearTimeout() method is below. Note that, the ID set by setTimeout() method needs to be passed into clearTimeout() method for it work.

<input type="button" value="Stop count!" onclick="stopCount()" />
<
script type="text/javascript">
function
stopCount()
{
clearTimeout(interval2);
}
</script>

0 comments:

Reference: Shahed Kazi at AspNetify.com