JavaScript Introduction | Browser Object Model | Timers

Timers

The window object provides the following methods so that a function can be called after a certain amount of time has passed.

  1. setTimeout()
  2. setInterval()

It also provides the following methods to cancel calls to functions scheduled in this way.

  1. clearTimeout()
  2. clearInterval()

setTimeout() Method

The setTimeout() method calls the specified function after the specified amount of time has passed.

Syntax

window.setTimeout(functionToCall, delayTime);

If this method is called successfully, it returns the configured timeoutID. This method lets you set the delay time in milliseconds.

function startTimeout() {
    setTimeout(printCurrentDate, 2000);
}
function printCurrentDate() {
    document.getElementById("date").innerHTML = new Date();
}

setInterval() Method

The setInterval() method repeatedly calls the specified function at the specified time interval.

Syntax

window.setInterval(functionToCall, delayTime);

If this method is called successfully, it returns the configured timeoutID. This method lets you set the interval in milliseconds.

Syntax

function startInterval() {
    setInterval(printCurrentDate, 2000);
}
function printCurrentDate() {
    document.getElementById("date").innerHTML += new Date() + "<br>";
}

clearTimeout() Method

If you pass the return value of setTimeout() as an argument to clearTimeout(), you can cancel the scheduled function call.

Syntax

window.clearTimeout(timeoutID);

This method must be executed before the function is called by setTimeout() in order to cancel the call. If you call this method after the function has already been called, it does nothing.

var timeoutId;
function startTimeout() {
    timeoutId = setTimeout(printCurrentDate, 2000);
}
function cancelTimeout() {
    clearTimeout(timeoutId);
}
function printCurrentDate() {
    document.getElementById("date").innerHTML += new Date() + "<br>";
}

clearInterval() Method

If you pass the return value of setInterval() as an argument to clearInterval(), you can cancel repeated function calls.

Syntax

window.clearInterval(timeoutID);
var timeoutId;
function startInterval() {
    timeoutId = setInterval(printCurrentDate, 2000);
}
function cancelInterval() {
    clearInterval(timeoutId);
}
function printCurrentDate() {
    document.getElementById("date").innerHTML += new Date() + "<br>";
}