Put JavaScript To Sleep

Every Java programmer will tell you that you can pause a program using the sleep static method of the Thread class.

Thread.sleep(milliseconds);

JavaScript does not have a wait or sleep method but instead provides the setTimeout and setInterval functions. Here is some JavaScript code to demonstrate the setTimeout function:

setTimeout('alert("Hello, World")', 4000);
alert('Hello, Web');

The Hello, World message will display after 4 seconds, and after the Hello, Web message. In essence, this function treats a piece of JavaScript code as a child and gives it a ‘time out.’ In contrast, the setInterval method will repeatedly execute a piece of code at a given time interval in milliseconds until you stop it. When compare side by side, I rather use the setTimeout function. Here is a recursive-like example using the setTimeout function that mimics setInterval.

var myColors = new Array(
    '#000000',
    '#FF0000',
    '#00FF00',
    '#0000FF',
    '#FFFFFF'
    );

function myFunx(index) {
    if(!index || index > myColors.length) {
        index = 0;
    }
    setTimeout('myFunx('+(index+1)+')', 2000);
    document.bgColor=myColors[index];
}

myFunx();

The example above updates the background color every other second. Don’t try this at home unless you are a trained professional or are writing trivial JavaScript examples.

Enjoy. Share. Be Happy.
  • Twitter
  • Facebook
  • StumbleUpon
  • del.icio.us
  • Tumblr
  • Google Bookmarks
  • FriendFeed
  • Yahoo! Buzz
  • Reddit
  • Digg
  • HackerNews
  • Suggest to Techmeme via Twitter
  • LinkedIn
  • Ping.fm
  • Identi.ca
  • Mixx
  • Furl

Related posts:

  1. The Anatomy of a JavaScript Bookmarklet
  2. Unobtrusive JavaScript with Prototype and Behavior
  3. Chain JavaScript Events
  4. Generate Pretty GWT JavaScript
  5. Evolution of a JavaScript Coder

This entry was posted in Java, JavaScript, TechKnow. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

4 Comments

  1. Mohan J V
    Posted July 23, 2007 at 12:55 am | Permalink

    nice .. that was helpful

  2. Posted April 25, 2008 at 5:21 am | Permalink

    To stop the timer use clearTimeout(id) with id = setTimeout(…).

    greetings

  3. GH
    Posted June 6, 2008 at 6:31 am | Permalink

    The clearing of the timeout id is necessary especially where you’re creating several timeout requests – I’ve seen pages in IE run out of memory due to timeout operation leaks.

  4. Sirish
    Posted September 19, 2008 at 7:56 am | Permalink

    Thanks, it helps me a lot

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*