Most of the time, JavaScript code is synchronous (running line by line). However, some tasks take time (loading images, fetching API data). Asynchronous means "I will finish later!".
In synchronous programming, the program waits for each task to finish before moving to the next. In asynchronous programming, the program starts a task and continues to the next task while waiting for the previous one to finish.
The setTimeout() method is a perfect example of asynchronous behavior. It
executes a function after a specified number of milliseconds.
console.log("Start");
setTimeout(function() {
console.log("Middle (after 3 seconds)");
}, 3000);
console.log("End");
// Result:
// Start
// End
// Middle (after 3 seconds)
The setInterval() method repeats a function every specified number of
milliseconds.
setInterval(myTimer, 1000);
function myTimer() {
const d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
Modern web applications rely on fetching data from external servers. If JavaScript was strictly synchronous, the entire browser would freeze (user wouldn't be able to click or scroll) while waiting for that data to arrive.
setTimeout() runs a task once after a delaysetInterval() runs a task repeatedly at fixed intervals