0

I want to run a delay function for five seconds in JavaScript which will print "Hello" in the console after every second for five times.

Similar Python Code:

from time import delay

for I in range(5):
    print("Hello")
    delay(1)

The above code will print "Hello" five times with one second delay between each print.

Now I want to do similar kind of operation in JS.

Now in JS we have setTimeout function which will call a function after after a specified time. The following code will print "Hello" in the console after 1 second interval.

setTimeout(function(){ 
      console.log("Hello"); 
     }, 1000);

How can I run this code that will print 'Hello' in the console five times with an one second delay between each print?

NB: I tried to pass this function inside a for loop, but it did not work.

Shovon
  • 32
  • 7
  • 1
    Does this answer your question? [Repeating setTimeout](https://stackoverflow.com/questions/11624078/repeating-settimeout) – jsotola Nov 03 '20 at 07:53

3 Answers3

1

Try like this:

var count = 5;

printWithDelay();

function printWithDelay() {
  setTimeout(function() {
    console.log("Hello");

    count--;

    if (0 < count) {
      printWithDelay();
    };
  }, 1000);
};

In JavaScript, 'setTimeout' runs after the code that follows it, so the next iteration of the loop needs to be called from within the callback function for this to work.

sbgib
  • 5,580
  • 3
  • 19
  • 26
0

Use setInterval, this should get your job done!

const test = setInterval(() => console.log("Hello"), 1000);

And then after 5seconds remove interval

setTimeout( () => clearInterval(test), 5000)

const test = setInterval(() => document.body.innerText += "Hello", 1000);
setTimeout( () => clearInterval(test), 5000);

NOTE: The first console.log() will happen after a second, if you want it immediately just put one console.log() outside the setInterval.

Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
0

JavaScript, unlike PHP and Python, is asynchronous. The event loop is sensitive to anything that blocks it. However, there are ways to achieve what you want.

setInterval

With setInterval, you can build a wrapper it and use it.

function repeatFunction(func, delay, repeat) {

  let counter = 0;
  let interval = setInterval(() => {

    if (repeat !== counter) {
      func();
      counter++;
    } else {
      clearInterval(interval)
    }
  }, delay);

}


repeatFunction(() => console.log(5), 1000, 4)

async/await syntax

The other option is using async/await with Promises (recommended)

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}


(async() => {

  for (let i = 0; i < 5; i++) {
    console.log(i);
    await sleep(1000);
  }
  
  console.log('done')

})();
Adam Azad
  • 11,171
  • 5
  • 29
  • 70