16. Asynchronous Javascript - Part 1 : setTimeout() , setInterval() , event loop
» Asynchronous JavaScript is a programming technique that allows certain operations to be executed without blocking the main thread (the execution flow of JavaScript).
» This means that while JavaScript is waiting for a long-running task (e.g., fetching data from a server), it can continue executing other code using callbacks, promises, and async/await.
» JavaScript is synchronous(code execute line by line) , single-threaded, and blocking by default. However, it can handle asynchronous operations using features like:
✅ Callbacks
✅ Promises
✅ Async/Await
✅ Web APIs (setTimeout, fetch, etc.)
✅ Event Loop & Task Queue
setTimeout()
– Execute After a DelayThe
setTimeout()
method executes a function once after a specified delay (in milliseconds).console.log("Start"); setTimeout(() => { //setTime out is node function, it first came in callback queue(not in call stack) and execute after call stack is empty console.log("Hello after 2 seconds"); }, 2000); console.log("End"); /*Output Start End Hello after 2 seconds
setTimeout()
does not block the execution of the remaining code.The callback function runs asynchronously after 2 seconds.
use setTimeout() with arguments
function greet(name) { console.log(`Hello, ${name}!`); } setTimeout(greet, 3000, "John"); // Output (after 3 seconds): "Hello, John!"
setInterval()
The
setInterval()
method executes a function repeatedly at fixed intervals.let count = 1; const intervalId = setInterval(() => { console.log(`Count: ${count}`); count++; if (count > 5) { clearInterval(intervalId); // Stop after 5 iterations } }, 1000);
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Event loop
The event loop is a mechenism in JS that ensures asynchronous tasks are executed without blocking the main thread.
Event Loop Execution Order
Synchronous Code – Executes first.
Microtasks Queue (
Promises
) – Executes next.Macrotasks(callback queue) Queue (
setTimeout()
,setInterval()
, etc.) – Executes last.Example:
console.log("Start"); setTimeout(() => console.log("Timeout Callback"), 0); Promise.resolve().then(() => console.log("Promise Callback")); console.log("End"); /* Output Start End Promise Callback Timeout Callback
Why?
"Start"
and"End"
execute first (synchronous code).The Promise callback runs before
setTimeout()
(because promises are microtasks).setTimeout()
executes last (macrotask queue).
How do you stop setTimeout()
and setInterval()
?
Use
clearTimeout(timeoutId)
to cancelsetTimeout()
.Use
clearInterval(intervalId)
to cancelsetInterval()
.