JavaScript features a couple of methods that lets you run a piece of JavaScript code (javascript function) at some point in the future. These methods are:

In this tutorial, I'll explain how setTimetout() method works, and give a real world example. You may find the details of setInterval() method in JavaScript setInterval Function - JavaScript Timing Events


window.setTimeout() method allows you to specify a piece of JavaScript code (expression) will be run after specified number of miliseconds from when the setTimeout() method is called.


var t = setTimeout ( expression, timeout );

The setTimeout() method returns a numeric timeout ID which can be used to refer the timeout to use with clearTimeout method. The first parameter (expression) of setTimeout() is a string containing a javascript statement. The statement could be a call to a JavaScript function like "delayedAlert();" or a  statement like "alert('This alert is delayed.');". The second parameter (timeout), indicates the number of miliseconds to pass before executing the expression.


      <script type="text/javascript">
        function delayedAlert()
           var t=setTimeout("alert('You pressed the button 5 seconds ago!')",5000)
         <input type="button" value="Display Delayed Alert"

An alert box will be shown 5 seconds later when you clicked the button.


Sometimes it's useful to be able to cancel a timer before it goes off. The clearTimeout() method lets us do exactly that. Its syntax is:

clearTimeout ( timeoutId );

where timeoutId is the ID of the timeout as returned from the setTimeout() method call.

Want automatic updates? Subscribe to our RSS feed or
Get Email Updates sent directly to your inbox!

Currently rated 5.0 by 4 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


November 21. 2007 05:13

You state that the "first parameter (expression) of setTimeout() is a string containing a javascript statement" - while setTimeout and setInterval do allow you to do this, you can pass a function pointer or an anonymous function in as well (and perhaps that would be better anyway - strings as code is a nice feature, but can get ugly). So, here are examples of both:

function Foo{
   // do something
setTimeout(Foo, 100);


   // do something here
}, 100);

Jason Bunting | Reply

October 27. 2009 14:28

Thank you for your help!

fast cash loans | Reply

December 26. 2009 19:27

Like your writing! Still you can do some things to improve it.

cash loans | Reply

February 10. 2010 13:25

Useful info. Hope to see more good posts in the future.

SEO | Reply

Add comment

(Will not be displayed!)