1. setTimeout()
The setTimeout() method executes a callback function after a specified delay.
setTimeout(() => {
console.log("Hello JavaScript!");
}, 2000);
Here, the message is printed after approximately 2 seconds.
2. Synchronous JavaScript
Synchronous code executes one statement at a time, in order. Each statement normally finishes before the next one runs.
console.log("First");
console.log("Second");
console.log("Third");
Output:
First
Second
Third
3. Asynchronous JavaScript
Asynchronous operations allow JavaScript to continue running other code while waiting for certain operations to complete.
console.log("Start");
setTimeout(() => {
console.log("Inside timeout");
}, 2000);
console.log("End");
Output:
Start
End
Inside timeout
This helped me understand how JavaScript handles delayed operations.
`
4. Promise
`
A Promise is a built-in JavaScript object that represents the eventual success or failure of an asynchronous operation.
A Promise can be in one of three states:
Pending — the operation is still in progress.
Fulfilled — the operation completed successfully.
Rejected — the operation failed.
`
let myPromise = new Promise((resolve, reject) => {
resolve("Task completed!");
});
myPromise.then((result) => {
console.log(result);
});`
Output:
Task completed!
resolve() fullfills the promise and .then() handles the fullfilled result.
Today I learned the difference between synchronous and asynchronous JavaScript, how setTimeout() schedules a callback, and how Promises represent the result of an asynchronous operation.
These concepts are useful when fetching API data and working with my e-commerce website.
Top comments (0)