setInterval()
In this chapter you will learn:
Timer
setInterval()
executes the code repeatedly at
specific time intervals until the interval is canceled or
the page is unloaded.
The setInterval()
method accepts:
- the code to execute
- the milliseconds to wait between executions.
<!DOCTYPE HTML> <!-- j ava 2 s. c o m-->
<html>
<body>
<script type="text/javascript">
setInterval(function() {
document.writeln("Hello world!");
}, 1000);
</script>
</body>
</html>
Clear the timer
The setInterval()
method returns an interval ID.
We can use the ID to cancel the interval with
clearInterval()
method.
<!DOCTYPE HTML> <!-- jav a 2s . co m-->
<html>
<body>
<script type="text/javascript">
var num = 0;
var max = 10;
var intervalId = null;
function incrementNumber() {
document.writeln(num++);
//if the max has been reached,
//cancel all pending executions
if (num == max) {
clearInterval(intervalId);
document.writeln("Done");
}
}
intervalId = setInterval(incrementNumber, 500);
</script>
</body>
</html>
Next chapter...
What you will learn in the next chapter:
Home » Javascript Tutorial » Window