How to set Maximum Execution Time for a Promise Await in JavaScript ?
Last Updated :
17 Apr, 2024
In JavaScript, asynchronous operations are more common, often implemented using promises and async/await syntax. However, there are certain scenarios where we want to set the execution times for these asynchronous operations to prevent them from running indefinitely. In this article, we'll explore various ways to set the maximum execution time for a Promise await in JavaScript.
Using Promise.race() with a Timeout Promise
In this method, we'll use Promise.race() method. This method accepts an iterable of promises as its input and returns a new promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects. In our context, the Promise.race() race between the original promise and a timeout promise and whichever resolves or rejects first is returned.
Example: In this example, we'll create a Promise that simply returns a JavaScript object after a given timeout. We'll use Promise.race to set the maximum execution time.
JavaScript
function fetchData() {
return new Promise((resolve, reject) => {
// Simulating an asynchronous operation
setTimeout(() => {
const data = { example: "data" };
resolve(data);
}, 6000);
// Resolves after 6 seconds
});
}
function withTimeout(promise, timeout) {
return Promise
.race([
promise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error('Timeout')), timeout)
)
]);
}
async function executeFunction() {
try {
const data = await withTimeout(fetchData(), 5000);
// 5000 milliseconds timeout
console.log(data);
// Log fetched data to the console
} catch (err) {
console.error(err);
}
}
executeFunction();
Output:

Using setTimeout() method and a flag
Here we use setTimeout() method along with a completion flag to set the maximum execution time. If the data fetching operation takes longer than the set timeout, an error shall be thrown. Otherwise, if the data is fetched successfully within the timeout period, the fetched data will be logged to the console.
Example: In this example, we'll create a mainFunction() which is responsible for fetching data asynchronously using fetchData() function. We set a timeout using setTimeout() method for 7 seconds. If the operation doesn't complete within this timeout, an error message is thrown.
JavaScript
function fetchData() {
return new Promise((resolve, reject) => {
// Simulating an asynchronous operation
setTimeout(() => {
const data = { example: "data" };
resolve(data);
}, 5000); // Resolves after 5 seconds
});
}
async function mainFunction() {
let completed = false;
const timeout = 7000; // 7000 milliseconds timeout
setTimeout(() => {
if (!completed) {
console.error(new Error('Timeout'));
}
}, timeout);
try {
const data = await fetchData();
console.log(data); // Log fetched data to the console
completed = true;
} catch (err) {
console.error(err);
}
}
mainFunction();
Output:

Similar Reads
How to Execute Multiple Promises Sequentially in JavaScript? In JavaScript, executing multiple promises sequentially refers to running asynchronous tasks in a specific order, ensuring each task is completed before the next begins. This is essential when tasks depend on the results of previous ones, ensuring correct flow and preventing unexpected behavior.Foll
4 min read
Explain Promise.race() with async-await in JavaScript In this article, we will try to understand how we may implement Promise.race() method with async-await in JavaScript with the help of certain coding examples as well as theoretical explanations. Let us first quickly understand how we may implement Promise.race() method. This method is one of the mos
3 min read
How to run a given array of promises in series in JavaScript ? Given an array of Promises, we have to run that in a series. To do this task, we can use then(), to run the next promise, after the completion of a promise. Approach: The then() method returns a Promise, which helps us to chain promises/methods. The Promise.resolve() method executes the first callba
3 min read
How to Convert Callback to Promise in JavaScript ? Asynchronous programming in JavaScript often involves the use of callbacks. However, callbacks can lead to callback hell and make the code harder to read and maintain. Promises provide a cleaner way to handle asynchronous operations. Converting existing callback-based code to use promises can improv
2 min read
How to wait for multiple Promises in JavaScript ? Waiting for multiple promises in JavaScript involves using Promise.all() or Promise.allSettled() methods. These methods accept an array of promises as input. Promise.all() waits for all promises to either resolve or reject, providing a single promise that resolves with an array of results or rejects
3 min read
How to delay a loop in JavaScript using async/await with Promise ? In JavaScript, you can delay a loop by using async/await with Promise. By wrapping a setTimeout() inside a Promise and using await, you can pause execution at each iteration, creating delays between loop iterations for asynchronous tasks without blocking the main thread.What is async and await?async
2 min read