I want to create a function that prints ‘Hello, World!’ every second for 5 minutes, and after 5 minutes, this function will stop for 1 minute. I want to create a loop like this with setTimeout and setInterval, but I couldn’t. Can anyone help me?
const helloWorld = () => console.log("Hello, World!")
const stopSayHello = () => console.log("Stopped for a minute!")
The HelloWorld function will run every second for 5 minutes. After 5 minutes, the stopSayHello function will run for a minute. Then, this loop will continue.
4
Answers
You can have a function
startTimer
that will initiate the procedure…it will use
setInterval
to invokehelloWorld
each second.. while keeping track of the number of times it occurred. When such counter hits5*60
(1 minute) it clears the interval and prints it will be waiting for 1 minute.. by doingsetTimeout
and restarting the wholestartTimer
after such amount of time.The question is: such approach will overflow the call stack? Legit question but the
setTimeout
is expected to return immediately anwyay so there’s no infinite calls through the stack.Here we go:
I add code below.
This code sets up an initial setInterval to call the helloWorld function every second. After 5 minutes (300,000 milliseconds), it clears the interval, prints the stop message, and sets a setTimeout to restart the loop after 1 minute (60,000 milliseconds). This process repeats indefinitely.