setTimeout()

In this chapter you will learn:

  1. How to create a time out timer
  2. How to stop a time out timer
  3. Time out for a value

Time out timer

setTimeout() executes code after a specified amount of time.

  • setTimeout() method accepts two arguments:
  • the code to execute
  • the number of time (in milliseconds) to wait.

The first argument can be either a string containing JavaScript code or a function.

The following code runs an document.writeln after 1 second:

<!DOCTYPE HTML> <!-- j  av  a  2  s  .  co m-->
<html> 
    <body> 
        <script type="text/javascript"> 
    setTimeout(function() { 
       document.writeln("Hello world!"); 
       }, 
      1000
    ); 
        </script> 
    </body> 
</html>

Click to view the demo

Stop a time out timer

setTimeout() returns a numeric ID for the timeout. The ID can be used to cancel the timeout. To cancel a pending timeout, use the clearTimeout() method and pass in the timeout ID:

<!DOCTYPE HTML> <!--from j a v a 2s .c om-->
<html> 
    <body> 
        <script type="text/javascript"> 
            var timeoutId = setTimeout(function() { 
                document.writeln("Hello world!"); 
                }, 1000); 
            
            clearTimeout(timeoutId); 

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

Click to view the demo

Time out for a value

The following code set the timeout according to a value:

<!DOCTYPE HTML> <!-- jav a  2  s. c  om-->
<html> 
<body> 
<script type="text/javascript"> 
var num = 0; 
var max = 10; 
function incrementNumber() { 
    document.writeln(num++);  
    //if the max has not been reached, 
    //set another timeout 
    if (num < max) { 
        setTimeout(incrementNumber, 500); 
    } else { 
        document.writeln("Done"); 
    } 
} 
setTimeout(incrementNumber, 500); 

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

Click to view the demo

Next chapter...

What you will learn in the next chapter:

  1. How to use History object
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()