JavaScript Timing

W3schools JavaScript Timing Events


Use setTimeout(function, milliseconds) to make a function run after a delay.

Use setInterval(function, milliseconds) to make a function repeat every so often.

(1 second = 1000 milliseconds)

Example 1: change innerHTML after 3 seconds:

element = document.getElementById('myElement');
setTimeout(update, 3000);

function update() {
    element.innerHTML = "Text is updated!";
}

Example 2: update a timer every 1 second:

var t = 0;
seconds = document.getElementById('seconds');
setInterval(tick, 1000);

function tick() {
    t = t + 1;
    seconds.innerHTML = "Time: " + t;
}