2

I am wondering if there is a way to make a setTimeout (or some equivalent) in JavaScript that would not move on to the next line until the time was up. For example is there a way to make the below code work as intended?

var cntr = 0;

while(cntr < 25) {
    setTimeout(200); //wait 200ms to continue to next line
    console.log(cntr); //or some other task
    cntr++;
}

Thank you in advance for any answers I receive!

Pete K.
  • 82
  • 2
  • 11

3 Answers3

4

setTimeout can never be synchronous. But you can use recursion to achieve what you want -

var cntr = 0

function printCounter() {
  console.log(cntr)
  cntr++
  if(cntr < 25) {
    setTimeout(printCounter, 200)
  }
}

setTimeout(printCounter, 200)
Mukesh Soni
  • 6,192
  • 2
  • 25
  • 34
2

The closest you can get is with using async/await. The issue here is that it isn't supported in many browsers, so depending on what browsers you want to support this may not be a good solution.

I know this works in the most recent chrome browser (which is where I tested it), and should work in node 7.

// Tell the browser that this function is asynchronous
async function myFunc() {
    // Await for the promise to resolve
    await new Promise((resolve) => {
        setTimeout(() => {
            // Resolve the promise
            resolve(console.log('hello'));
        }, 3000);
    });
    // Once the promise gets resolved continue on
    console.log('hi');
}

// Call the function
myFunc();
Get Off My Lawn
  • 27,770
  • 29
  • 134
  • 260
-1

Have you tried the 'SetInterval()' function ?

 setInterval(loop(), 200);

   function loop() {
       console.log(cntr);
       cntr++;
   }

Every 200ms, something occurs.

EricF
  • 121
  • 1
  • 16