The accepted answer is incorrect and will just block the page/tab, either permanently or for a specific amount of time (assuming the browser doesn't kill it or freeze).
Based on your original code, you could calculate for how long the loop has been running on each iteration and use that in its condition:
const msToRun = 2000 // 2 seconds
// const msToRun = 600000 // 10 minutes
const t0 = performance.now() // or Date.now()
let flag = false;
let callsPerformed = 0
while (!flag) {
++callsPerformed;
if (performance.now() - t0 >= msToRun) {
flag = true;
}
}
console.log(`${ callsPerformed } calls made.`)
However, that's probably a bad idea because JavaScript's runtime is single-threaded and based on an event loop that runs to completion, meaning each item in the event loop's queue needs to be completed before the next one can be processed (the loop as a whole, rather than the individual iterations, is a single item in that queue).
From MDN:
Each message is processed completely before any other message is processed.
This offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be preempted and will run entirely before any other code runs (and can modify data the function manipulates). This differs from C, for instance, where if a function runs in a thread, it may be stopped at any point by the runtime system to run some other code in another thread.
A downside of this model is that if a message takes too long to complete, the web application is unable to process user interactions like click or scroll. The browser mitigates this with the "a script is taking too long to run" dialog. A good practice to follow is to make message processing short and if possible cut down one message into several messages.
This means that in the example above (as well as ChrisC's and yusufaytas' answers), the while
loops block the event loop, preventing any other operation queued to be executed (making the page unresponsive).
This is also one of the reasons why setTimeout
's delay is not guaranteed (they might actually take longer).
This series of posts might be a better start to understand that than the MDN documentation IMO: ✨♻️ JavaScript Visualized: Event Loop
⏳ Run loop for a fixed amount of time:
If what you want is to run the loop for a certain amount of time, you can do that in both a sync (blocking) and async (non-blocking) way.
You'll notice some differences in both responsiveness of the page while the loop is running as well as how many iterations you are able to run within a specific timeframe.
🛑 Run loop for a fixed amount of time - Blocking (same as the example above):
const msToRun = 2000 // 2 seconds
const t0 = performance.now() // or Date.now()
let iterations = 0
setTimeout(() => {
console.log(`This won't be logged until the loop is over.`)
}, 0)
while ((performance.now() - t0) < msToRun) {
++iterations
}
console.log(`Loop run for ${ iterations } iterations.`)
body {
height: 100vh;
margin: 0;
}
body:hover {
background: yellow;
}
🚦 Run "loop" for a fixed amount of time - Non-blocking (setInterval):
const msToRun = 2000 // 2 seconds
const t0 = performance.now() // or Date.now()
let iterations = 0
setTimeout(() => {
console.log(`This will be logged before the loop is over.`)
}, 0)
const intervalID = setInterval(() => {
++iterations
if (performance.now() - t0 >= msToRun) {
clearInterval(intervalID)
console.log(`Loop run for ${ iterations } iterations.`)
}
})
body {
height: 100vh;
margin: 0;
}
body:hover {
background: yellow;
}
🚥 Run "loop" for a fixed amount of time - Non-blocking (setTimeout):
const msToRun = 2000 // 2 seconds
const t0 = performance.now() // or Date.now()
let iterations = 0
setTimeout(() => {
console.log(`This will be logged before the loop is over.`)
}, 0)
function runIteration() {
++iterations
if (performance.now() - t0 < msToRun) setTimeout(runIteration)
else console.log(`Loop run for ${ iterations } iterations.`)
}
runIteration()
body {
height: 100vh;
margin: 0;
}
body:hover {
background: yellow;
}
person
is added topeople
, then make the call. – SignificancesetInterval()
performs an action repeatedly after a certain amount of time. So if you'd likecall(people)
to be called every 10 seconds, you could do that. That way a queue could be built up in people, then executed at intervals. – Significance