1. 8.5 Timers
    2. 8.6 User prompts
      1. 8.6.1 Simple dialogs
      2. 8.6.2 Printing

8.5 Timers

The setTimeout() and setInterval() methods allow authors to schedule timer-based callbacks.

handle = self . setTimeout( handler [, timeout [, arguments... ] ] )

Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler.

handle = self . setTimeout( code [, timeout ] )

Schedules a timeout to compile and run code after timeout milliseconds.

self . clearTimeout( handle )

Cancels the timeout set with setTimeout() or setInterval() identified by handle.

handle = self . setInterval( handler [, timeout [, arguments... ] ] )

Schedules a timeout to run handler every timeout milliseconds. Any arguments are passed straight through to the handler.

handle = self . setInterval( code [, timeout ] )

Schedules a timeout to compile and run code every timeout milliseconds.

self . clearInterval( handle )

Cancels the timeout set with setInterval() or setTimeout() identified by handle.

Timers can be nested; after five such nested timers, however, the interval is forced to be at least four milliseconds.

This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.

To run tasks of several milliseconds back to back without any delay, while still yielding back to the browser to avoid starving the user interface (and to avoid the browser killing the script for hogging the CPU), simply queue the next timer before performing work:

function doExpensiveWork() {
  var done = false;
  // ...
  // this part of the function takes up to five milliseconds
  // set done to true if we're done
  // ...
  return done;
}

function rescheduleWork() {
  var handle = setTimeout(rescheduleWork, 0); // preschedule next iteration
  if (doExpensiveWork())
    clearTimeout(handle); // clear the timeout if we don't need it
}

function scheduleWork() {
  setTimeout(rescheduleWork, 0);
}

scheduleWork(); // queues a task to do lots of work

8.6 User prompts

8.6.1 Simple dialogs

window . alert(message)

Displays a modal alert with the given message, and waits for the user to dismiss it.

result = window . confirm(message)

Displays a modal OK/Cancel prompt with the given message, waits for the user to dismiss it, and returns true if the user clicks OK and false if the user clicks Cancel.

result = window . prompt(message [, default] )

Displays a modal text control prompt with the given message, waits for the user to dismiss it, and returns the value that the user entered. If the user cancels the prompt, then returns null instead. If the second argument is present, then the given value is used as a default.

Logic that depends on tasks or microtasks, such as media elements loading their media data, are stalled when these methods are invoked.

8.6.2 Printing

window . print()

Prompts the user to print the page.