I have created an infinite loop to check if a certain time is met and change my interface accordingly.
function infiniteloop(){
let now = moment();
start = moment(myStartTime);
end = moment(myEndTime);
if (now.isBetween(start, end)) {
console.log('This is happening now')
} else {
console.log('This is not happening now')
}
setTimeout(infiniteloop, 5000);
}
infiniteloop()
is called when my page renders. As the variables myStartTims
and myEndTime
may change, it is necessary to call that function again when they change. But then it runs multiple times.
So I tried to call it with
clearTimeout(infiniteloop);
infiniteloop();
But that doesn’t do the Trick. How can I ensure the loop is stopped and called again?
2
Answers
Here’s a
setRepeating
that is subtly different fromsetInterval
. AsetInterval
call will do something at regular intervals regardless of how long the function itself takes. Whereas thissetRepeating
call will run the function, then after the function is done, it will wait for the full interval period before running it again.It’s the difference between baking a cake, then waiting one minute, then baking another cake, vs. trying to bake one cake every minute.
It’s also functionally different from
setInterval
in that this function returns a cancellation function instead of an id, which is a little cleaner, IMO. Because the only thing you ever do with a timer id is cancel the timer.To "restart" this, just call
setRepeating
again and get a new cancel function.