Javascript run loop for specified time

Discussion RoomCategory: General QuestionJavascript run loop for specified time
Admin Staff asked 9 months ago

In JavaScript, you cannot run a loop for a specific amount of time directly using a standard loop construct like `while` because JavaScript is single-threaded, and a blocking loop like the one you’ve described would prevent other tasks, including UI updates, from executing during that time.
However, you can achieve your goal using a combination of asynchronous functions, timers, and the `Promise` pattern. Here’s how you could implement it:

async function makeCallsForTimeLimit() {
const startTime = Date.now();
const timeLimit = 10 * 60 * 1000; // 10 minutes in milliseconds
while (Date.now() - startTime < timeLimit) {
await call(people); // Assuming `call` is an asynchronous function
// You can insert additional logic here if needed
await sleep(1000); // Wait for 1 second before making the next call
}
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
makeCallsForTimeLimit().then(() => {
console.log("Time limit reached. Calls completed.");
});

In this example, the `makeCallsForTimeLimit` function will repeatedly call the `call` function and wait for a second before making the next call. It will keep doing this until the specified time limit (10 minutes) has passed. The `sleep` function is used to pause execution for a specified number of milliseconds.
Keep in mind that JavaScript’s single-threaded nature means you shouldn’t block the event loop for extended periods. Using asynchronous patterns, such as Promises and timers, allows your program to continue handling other tasks and events while your loop is running.
Also, be cautious when using loops like this, especially when interacting with external services or APIs, as you may want to handle errors and retries appropriately to ensure robustness in real-world scenarios.

Scroll to Top