Concepts 🚀 Project 🧮 Labs
📚 Learn / Frontend / setInterval & setTimeout

setInterval & setTimeout

Schedule code to run later. setTimeout runs once; setInterval runs every N ms. Clear with clear*.

Code example

// run once after 1 second
setTimeout(() => {
  console.log('hello after 1s');
}, 1000);

// run every 1 second (live clock)
setInterval(() => {
  document.getElementById('clock').textContent =
    new Date().toLocaleTimeString();
}, 1000);

// stop an interval
const id = setInterval(..., 1000);
clearInterval(id);

How it works

setTimeout(fn, ms) runs fn once after ms milliseconds. setInterval(fn, ms) runs fn every ms milliseconds forever (until cleared). Both return an ID you can pass to clearTimeout / clearInterval to cancel. The classic use case for setInterval is a live clock: every 1000ms, read the current time and update the DOM. Other uses: polling an API every 30s ( WS heartbeat), debouncing search input (wait 300ms after the user stops typing), auto-saving a draft every 10s. Always clear intervals when the component unmounts — otherwise they keep running in the background and leak memory.

🔍 Where this is used in OpenBenchML templates/realtime.html — 30s WS heartbeat. The user's example HTML — 1s live clock. Notebook — 250ms output flush interval.