Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Timers

A timer lets you run code not now but after some time, or repeat it at equal intervals. Timers power reminders, autosave, countdowns and pauses between actions.

setTimeout

The setTimeout() function calls the given function once after a given number of milliseconds. There are 1000 milliseconds in a second:

setTimeout(() => {
  console.log('Half a second has passed');
}, 500);
// Half a second has passed

The first argument is what to run, the second is the delay. A function you pass to another function so that it calls it later is called a callback.

Code does not wait for a timer

setTimeout() only sets the timer and returns straight away. The code after it runs before the function from the timer:

console.log('First');
 
setTimeout(() => {
  console.log('Third');
}, 300);
 
console.log('Second');
// First
// Second
// Third

The event loop from the previous lesson explains why.

A function by name and arguments

Instead of an arrow function you can pass an existing function by name — without parentheses. Its arguments are listed after the delay:

function greet(name) {
  console.log(`Hello, ${name}!`);
}
 
setTimeout(greet, 300, 'Anna');
// Hello, Anna!

Cancelling a timer

setTimeout() returns an identifier — the timer's number. Pass it to clearTimeout() and the function will not run:

const timer = setTimeout(() => {
  console.log('This will not be printed');
}, 500);
 
clearTimeout(timer);
console.log('Timer cancelled'); // Timer cancelled

This is how you cancel, say, an autosave when the user closes the form early.

setInterval

setInterval() calls a function again and again at equal intervals. clearInterval() with the interval's identifier stops it:

let count = 0;
 
const timer = setInterval(() => {
  count++;
  console.log(`Tick ${count}`);
 
  if (count === 3) {
    clearInterval(timer);
  }
}, 200);
// Tick 1
// Tick 2
// Tick 3

The delay is a minimum

A timer guarantees that the function runs no earlier than the given time, but it can run later if JavaScript is busy with other code:

const start = Date.now();
 
setTimeout(() => {
  console.log(Date.now() - start >= 100); // true
}, 100);

That is why timers are not suitable for precise timekeeping. A clock on a page reads the current time with Date.now() every time.

Common mistake

Passing the result of a call instead of a function. setTimeout(greet('Anna'), 1000) runs greet immediately, and the timer gets undefined. The correct way is to pass the function itself: setTimeout(() => greet('Anna'), 1000). And remember to stop intervals: a forgotten setInterval() keeps running as long as the tab is open.

Thanks for reading!

Donate to the site — we work hard for you.