Skip to content

Asynchronous Programming

In JavaScript, code runs line by line (synchronously).
But some operations (e.g., waiting a delay, loading an external resource, making an HTTP request) take time.

Asynchronous programming allows you to not block the program during these operations.
The rest of the code continues running, and the long task will be handled later when it’s ready.


setTimeout runs a function once after a specified delay (in milliseconds).

console.log("Start");
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);
console.log("End");
  • console.log("Start") → logs immediately
  • setTimeout is scheduled for 2000 ms (2s)
  • console.log("End") runs before the setTimeout callback
  • After 2 seconds, the function inside setTimeout executes

setInterval runs a function repeatedly at regular intervals.

let count = 0;
let interval = setInterval(() => {
count++;
console.log("Count:", count);
if (count >= 5) {
clearInterval(interval); // stops the loop
}
}, 1000);
  • The function runs every 1000 ms (1 second)
  • The counter increments on each run
  • When count reaches 5, clearInterval stops the loop

  • setTimeout → run a task once after a delay
    (e.g., show a notification after 5 seconds)
  • setInterval → run a task repeatedly
    (e.g., update a clock in real time)

  • Always clear an interval with clearInterval when it’s no longer needed (avoid infinite loops).
  • Avoid nesting too many setTimeout calls → prefer modern solutions like Promises or async/await.
  • Use asynchronous programming to keep an application responsive (do not block the UI).