Skip to content
techsnow

Async JavaScript

Timers

// run once after 2 seconds
const id = setTimeout(() => console.log("Hello later"), 2000);
clearTimeout(id); // cancel it

// run every second
let seconds = 0;
const timer = setInterval(() => {
  seconds++;
  console.log(seconds);
  if (seconds === 5) clearInterval(timer);
}, 1000);

JavaScript doesn't wait for timers. It schedules them and carries on with the next line. This is called asynchronous code.