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.

Related posts:

  1. The Anatomy of a JavaScript Bookmarklet
  2. JavaScript StackTrace With The console Object
  3. Unobtrusive JavaScript with Prototype and Behavior
  4. JavaScript Debugging With The console Object
  5. Chain JavaScript Events
  6. Evolution of a JavaScript Coder


6 Responses to “Put JavaScript To Sleep”

Leave a Reply