setInterval()

In this chapter you will learn:

  1. How to use timer in Javascript
  2. How to clear a timer

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>

Click to view the demo

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>

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to create a time out timer
  2. How to stop a time out timer
  3. Time out for a value
Home » Javascript Tutorial » Window
Window Object
alert()
close()
confirm()
find()
Window height and width
location
window.moveBy
window.moveTo
window.open()
window.print()
window.prompt()
resizeTo(x,y) and resizeBy(xDelta,yDelta)
window.scrollTo(x,y)
screenLeft, screenX, screenTop, screenY
setInterval()
setTimeout()