JavaScript is synchronous by default, which means it usually runs code line-by-line. With asynchronous features like callbacks and timers, JavaScript can handle tasks such as server requests, file reads, or delayed actions without blocking the rest of the code.
setTimeout() do not freeze the main thread.In asynchronous JavaScript, we often pass a function (callback) into another function. The callback is stored and executed later, typically when an async task (like a timer or API call) completes.
Common async tools:
setTimeout(callback, delay) – run callback once after delay ms.setInterval(callback, delay) – run callback repeatedly every delay ms.Here a function simulates fetching data and then runs a callback to process that data.
function fetchData(callback) {
setTimeout(() => {
console.log("Data fetched");
callback();
}, 2000);
}
function processData() {
console.log("Processing data...");
}
fetchData(processData);
This example shows that the code after setTimeout() continues to run immediately, while the callback runs later.
console.log("Start");
setTimeout(() => {
console.log("This runs later");
}, 2000);
console.log("End");
If you run the timing example, the console output will be:
StartEndThis runs later (after ~2 seconds)Even though setTimeout() appears between the two logs, its callback is scheduled to run later. JavaScript continues executing the rest of the code, then comes back to the callback after the delay.
setInterval().call the callback inside your async function when the work is done.setTimeout() when you need a one-time delay, and setInterval() for regular repeated tasks.setTimeout() calls.setInterval() to print a message every second, then stop it after 5 seconds using clearInterval().