window.setTimeout() or setTimeout()

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> 
<html> 
    <head> 
        <title>Example</title> 
    </head> 
    <body> 
        <script type="text/javascript"> 
    setTimeout(function() { 
                      document.writeln("Hello world!"); 
                   }, 
                   1000
    ); 


        </script> 
    </body> 
</html>
  
Click to view the demo

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> 
<html> 
    <head> 
        <title>Example</title> 
    </head> 
    <body> 
        <script type="text/javascript"> 
            var timeoutId = setTimeout(function() { 
                document.writeln("Hello world!"); 
                }, 1000); 
            
            clearTimeout(timeoutId); 

        </script> 
    </body> 
</html>
  
Click to view the demo

The following code set the timeout according to a value:

 
<!DOCTYPE HTML> 
<html> 
    <head> 
        <title>Example</title> 
    </head> 
    <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
Home 
  JavaScript Book 
    DOM  

Window:
  1. The Window Object
  2. The Window Events
  3. window.alert() or alert()
  4. window.close()
  5. window.confirm() or confirm()
  6. window.find() displays find dialog
  7. window's outer width and height, inner height and width
  8. window.location
  9. window.moveBy(distance, distance)
  10. window.moveTo(x,y) moves the window to the upper-left coordinate
  11. window.open()
  12. window.print()
  13. window.prompt() and prompt()
  14. window.resizeTo(x,y) and window.resizeBy(xDelta,yDelta)
  15. window.scrollTo(x,y)
  16. window.screenLeft, window.screenX, window.screenTop, window.screenY
  17. window.setInterval() or setInterval()
  18. window.setTimeout() or setTimeout()
  19. Pop-up Blockers