Home > Net >  How to set loop with pause in between each log
How to set loop with pause in between each log

Time:11-05

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.

CodePudding user response:

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

CodePudding user response:

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();
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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()
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

  • Related