Using Interrupts

JavaScript provides access to interrupts, a method by which you can ask the browser to call your code after a set period of time, or even to keep calling it at specified intervals. This gives you a means of handling background tasks such as Ajax communications, or even things like animating web elements.

There are two types of interrupt, setTimeout and setInterval, which have accompanying clearTimeout and clearInterval functions for turning them off again.

Using setTimeout

When you call setTimeout, you pass it some JavaScript code or the name of a function, and a value in milliseconds representing how long to wait before the code should be executed, like this:

setTimeout(dothis, 5000)

Your dothis function might look like this:

function dothis()
{
    alert('This is your wakeup alert!');
}

Note

In case you are wondering, you cannot simply specify alert() (with parens) as a function to be called by setTimeout, because the function would be executed immediately. Only when you provide a function name without argument parentheses (for example, alert) can you safely pass the function name, so that its code will be executed only when the timeout occurs.

Passing a string

When you need to provide an argument to a function, you can also pass a string value to the setTimeout function, which will not be executed until the correct time. For example:

setTimeout("alert('Hello!')", 5000)

In fact, you can provide as many lines of JavaScript code as you like, if you place a semicolon after each ...

Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.