CodeBlanks Logo Icon CodeBlanks

setTimeout and setInterval

Learn timers with setTimeout and setInterval.

setTimeout

To run a function after a delay, use setTimeout. It takes two parameters: the function to call and the delay in milliseconds.

Example: setTimeout(() => console.log("Hello"), 1000); prints "Hello" after one second. setTimeout returns a timer id; you can cancel the call with clearTimeout(id). Even with delay 0 the callback runs after sync code; this shows how the event loop works. To cancel a timer you write const id = setTimeout(...); clearTimeout(id);. Timers run in the background; they do not block the main code.

setInterval and clearInterval

To run a function repeatedly at intervals, use setInterval. setInterval(fn, 1000) calls the function every second. To stop it you need clearInterval(id).

Example: let count = 0; const id = setInterval(() => { count++; console.log(count); if (count >= 3) clearInterval(id); }, 100);. This increments a counter every 100 milliseconds; it stops at 3. setInterval returns an id; you pass it to clearInterval to break the loop. Otherwise the timer runs forever and the process does not exit. Designing a stop condition for every setInterval call is a good habit.

Practice Write sequential output with setTimeout

Set a timer with setTimeout(() => console.log("Done"), 0);. Print sync output with console.log("Started"). See the output order.

Starter code

index.js
// Print "Done" with setTimeout
// write here

// Print "Started"
// write here

Sample solution

index.js
setTimeout(() => console.log("Done"), 0);
console.log("Started");

Expected output

Başlatıldı
Bitti

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the setTimeout call

Question
setTimeout(() => console.log("Hazır"), ____);
Answer
setTimeout(() => console.log("Hazır"), 1000);

Explanation: 1000 milliseconds is 1 second.

2 What does setInterval return?

index.js
const id = setInterval(fn, 1000);
  • Bir Promise
  • A timer ID Correct answer
  • Bir Date nesnesi
  • Nothing

Explanation: setInterval returns a timer id.

3 Match each function to its tool

Term Meaning
setTimeout One-shot delay
setInterval Repeating interval
clearTimeout Cancel one-shot
clearInterval Cancel repeating

All lessons in Intermediate