How could I make a loop that pauses for a set amount of time before repeating?
I tried using setTimeout inside of a while loop but that didn't work.
JavaScript is monothreaded, so blocking is to be avoided, that is why so much effort was pourred into the language to standardise Promise and add async / await
This allow to pause code execution without blocking, here how you do it:
// Only available in Node v15+
import { setTimeout as pause } from 'timers/promises'
// if not in node:
const pause = delay => new Promise(s => setTimeout(s, delay))
async function sayHelloEverySeconds() {
while (true) {
await pause(1000) // 1 sec
console.log('hello')
}
}
sayHelloEverySeconds()
But for this exact function, it would be simpler to use setInterval directly:
setInterval(() => console.log('hello'), 1000)
this will execute the function every seconds
You don't need to use async/await functions or promises or a while loop. Call a function and have setTimeout call the function again after a set amount of time.
function loop(count = 0) {
console.log(count);
setTimeout(loop, 1000, ++count);
}
loop();