Asynchronous Programming
What is asynchronous programming?
Section titled “What is 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
Section titled “setTimeout”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");Explanation (setTimeout)
Section titled “Explanation (setTimeout)”console.log("Start")→ logs immediatelysetTimeoutis scheduled for 2000 ms (2s)console.log("End")runs before thesetTimeoutcallback- After 2 seconds, the function inside
setTimeoutexecutes
setInterval
Section titled “setInterval”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);Explanation (setInterval)
Section titled “Explanation (setInterval)”- The function runs every 1000 ms (1 second)
- The counter increments on each run
- When
countreaches 5,clearIntervalstops the loop
When to use
Section titled “When to use”- 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)
Best practices
Section titled “Best practices”- Always clear an interval with
clearIntervalwhen it’s no longer needed (avoid infinite loops). - Avoid nesting too many
setTimeoutcalls → prefer modern solutions like Promises or async/await. - Use asynchronous programming to keep an application responsive (do not block the UI).