How to use timer in Javascript

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> 
<html> 
    <body> 
        <script type="text/javascript"> 
            setInterval(function() { <!--  w  ww  .j av  a  2  s .  c  o  m-->
                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> 
<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"); 
                } <!--  w ww. j  a v a2  s.  c  om-->
            } 
            intervalId = setInterval(incrementNumber, 500); 


        </script> 
    </body> 
</html>

Click to view the demo





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window