The setTimeout() method is used to execute a block of code after a specified amount of time. It executes the code only once after the delay.
setTimeout(function, milliseconds);function: A function containing the block of code to execute.milliseconds: The time (in milliseconds) after which the function will be executed.
setTimeout(function() {
console.log("Executed after 2 seconds");
}, 2000);The setTimeout() method returns an intervalID, which is a positive integer representing the timer created.
A function in JavaScript is a block of code that performs a specific task when called.
function greet(name) {
console.log('Hi ' + name);
}
greet('Peter'); // Output: Hi PeterYou can also pass a function as an argument to another function. A function passed as an argument is known as a callback function.
function greet(name, callback) {
console.log('Hi ' + name);
callback();
}
// Callback function
function callMe() {
console.log('I am a callback function');
}
greet('Peter', callMe);Hi Peter
I am a callback function
In this example, the callMe() function is passed as a callback to the greet() function.
A Promise is used to handle asynchronous operations in JavaScript. It allows you to execute code asynchronously and provides a way to handle the result once the operation is complete.
- Pending: Initial state, the operation is not complete.
- Fulfilled: The operation is successfully completed.
- Rejected: The operation failed.
let promise = new Promise(function(resolve, reject) {
// some asynchronous task
let success = true;
if (success) {
resolve("Operation Successful");
} else {
reject("Operation Failed");
}
});
promise.then(function(result) {
console.log(result);
}).catch(function(error) {
console.log(error);
});Operation Successful
-
Promise.resolve(value)- Returns a
Promisethat is resolved with the given value.
Promise.resolve("Resolved!").then((value) => console.log(value)); // Output: Resolved!
- Returns a
-
Promise.reject(reason)- Returns a
Promisethat is rejected with the given reason.
Promise.reject("Error!").catch((error) => console.log(error)); // Output: Error!
- Returns a
-
Promise.all(iterable)- Returns a single
Promisethat resolves when all promises in the iterable have resolved.
Promise.all([Promise.resolve(1), Promise.resolve(2)]) .then((values) => console.log(values)); // Output: [1, 2]
- Returns a single
-
Promise.allSettled(iterable)- Returns a
Promisethat resolves after all promises have either resolved or rejected.
Promise.allSettled([Promise.resolve(1), Promise.reject("Error")]) .then((results) => console.log(results)); // Output: [{status: "fulfilled", value: 1}, {status: "rejected", reason: "Error"}]
- Returns a
-
Promise.race(iterable)- Returns a
Promisethat resolves or rejects as soon as one of the promises in the iterable resolves or rejects.
let p1 = new Promise((resolve) => setTimeout(resolve, 500, "One")); let p2 = new Promise((resolve) => setTimeout(resolve, 100, "Two")); Promise.race([p1, p2]).then((value) => console.log(value)); // Output: Two
- Returns a
-
Promise.any(iterable)- Returns a
Promisethat resolves as soon as any of the promises in the iterable fulfill.
Promise.any([Promise.reject("Error"), Promise.resolve("Success!")]) .then((value) => console.log(value)); // Output: Success!
- Returns a
-
Promise.prototype.then(onFulfilled, onRejected)- Used to schedule actions when the promise is fulfilled or rejected.
Promise.resolve("Success!").then((value) => console.log(value)); // Output: Success!
-
Promise.prototype.catch(onRejected)- Used to handle errors when the promise is rejected.
Promise.reject("Error!").catch((error) => console.log(error)); // Output: Error!
-
Promise.prototype.finally(onFinally)- Executes a block of code when the promise is settled, regardless of whether it was resolved or rejected.
Promise.resolve("Success!") .finally(() => console.log("Cleanup!")); // Output: Cleanup!
setTimeout(): Executes a function once after a delay.- Callback function: A function passed as an argument to another function.
- Promises: Handle asynchronous operations with states of pending, fulfilled, or rejected.
- Promise chaining: Allows handling multiple promises and their results sequentially or concurrently.