Asynchronous JavaScript
JavaScript is single-threaded,
meaning it executes code sequentially. However, many tasks (like fetching data
or waiting) are asynchronous — they happen in the background without blocking
the main program. JavaScript provides several ways to handle asynchronous
operations smoothly.
1.
setTimeout and setInterval
- setTimeout
runs a function once after a specified delay (in milliseconds).
setTimeout(()
=> {
console.log("This runs after 2
seconds");
},
2000);
- setInterval
runs a function repeatedly at specified intervals.
let
count = 0;
let
intervalId = setInterval(() => {
console.log("Repeating every 1
second");
count++;
if (count === 5) {
clearInterval(intervalId); // Stop after 5
times
}
},
1000);
2.
Callbacks
A callback is a function
passed as an argument to another function, to be executed later.
function
fetchData(callback) {
setTimeout(() => {
callback("Data loaded");
}, 1500);
}
fetchData((message)
=> {
console.log(message); // Output after 1.5
seconds: Data loaded
});
Note: Callbacks can lead to nested “callback hell” if overused.
3.
Promises
Promises represent a value that may
be available now, later, or never. They help handle async operations more
cleanly.
let
promise = new Promise((resolve, reject) => {
let success = true;
setTimeout(() => {
if (success) {
resolve("Promise resolved!");
} else {
reject("Promise rejected!");
}
}, 1000);
});
promise
.then(result => console.log(result))
.catch(error => console.log(error));
4.
async/await
async
and await provide a simpler syntax to work
with Promises, making asynchronous code look synchronous.
function
wait(ms) {
return new Promise(resolve => setTimeout(resolve,
ms));
}
async
function run() {
console.log("Start");
await wait(2000); // Wait 2 seconds
console.log("After 2 seconds");
}
run();