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

setTimeout()

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.

Syntax

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.

Example 

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

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

clearTimeout()

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.

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Currently rated 5.0 by 4 people

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




Comments

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);

or

setTimeout(function(){
// do something here
}, 100);

Jason Bunting

Add comment





(will not be displayed)








  • javascript
  • querystring
  • url parameters
  • parse querystring
  • delayed redirect
  • settimeout
  • focus
  • textbox
  • page load
  • after submit
  • set focus in asp.net 2.0/3.5
  • on page load
  • after postback
  • set control focus
  • postback
  • asp.net 1.x
  • substring
  • substr
  • javascript string methods
  • parsefloat
  • convert strings to numbers
  • parseint
  • javascript history
  • history.go
  • history.back
  • http requests
  • image maps
  • css sprites
  • external css
  • external javascript
  • compress javascript
  • javascript compression
  • ajaxcontroltoolkit
  • tab control
  • array
  • length
  • javascipt
  • lastmodified
  • mstsc
  • terminal services
  • remote desktop connections
  • null
  • undefined
  • array.join
  • string concatenation
  • setinterval
  • clearinterval
  • timing events
  • cleartimeout
  • javascript timing events
  • url redirection
  • location.href
  • location.replace
  • redirect
  • redirection
  • system.io.compression
  • viewstate compression
  • compress viewstate
  • gzipstream
  • loadpagestatefrompersistencemedium
  • savepagestatetopersistencemedium
  • form spam
  • captcha
  • prevent spam without captcha
  • url redirect
  • defaultbutton
  • enter key
  • default button
  • asp.net
  • 2.0
  • form
  • panel
  • 1.1
  • form submit
  • dopostback
  • onkeypress
  • onkeydown
  • onkeyup
  • javascript key events
  • keycode 13
  • disable enter key
  • int32.parse
  • convert.toint32
  • int32.tryparse
  • google
  • hoax
  • gmail
  • storage
  • counter
  • mail
  • visual studio 2005
  • vs 2008
  • copy
  • paste
  • clipboard data
  • static variables
  • application object
  • static property
  • server control
  • web file manager
  • iz web file manager
  • convert
  • parse
  • tryparse
  • file upload control
  • maxrequestlength
  • executiontimeout
  • httpruntime
  • asp.net 2.0
  • registering scripts
  • registerclientscript
  • registerstartupscript
  • cross-browser
  • events
  • improve web site performance
  • compression
  • caching
  • elmah
  • error logging
  • exception
  • error
  • httphandler
  • google sitemap generator
  • sitemap
  • internet information services
  • iis7
  • hosts file
  • localhost
  • windows vista
  • search engine optimization
  • seo
  • search engine friendly pages
  • headscriptmanager
  • class library
  • head
  • css
  • c#
  • iis
  • internet information services manager
  • 401.3 unauthorized
  • 500.0 internal server error
  • http error 500.19
  • google toolbar
  • yellow input fields
  • input
  • select
  • background color
  • mozilla firefox
  • medium trust
  • orcas
  • compileroptions
  • warninglevel
  • zyb
  • mobile phones
  • online backup service
  • online services
  • textarea
  • maxlength
  • limit input length
  • custom server control
  • internal error 2739
  • adobe cs3
  • adobe customer support
  • solution
  • error code 0x80004005
  • 500.19 internal server error
  • meta tags
  • keywords meta tag
  • meta
  • description meta tag
  • fake page rank domains
  • scammers
  • google page rank technology
  • ebay
  • general
  • title
  • page rank