简体   繁体   中英

How to set loop with pause in between each log

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();

If you do want to implement the setInterval (which I don't recommend), do it like this:

 async function sayHelloEverySeconds() { while (true) { await new Promise((res, rej) => { setTimeout(() => { console.log('hello') res() }, 1000) // 1 sec }) } } sayHelloEverySeconds()

Of course, as said above, use the setInterval(callback, timeInMS)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM