skip to Main Content

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 myStartTimsand myEndTimemay 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


  1. let timeoutId
    
    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')
       }
       timeoutId = setTimeout(infiniteloop, 5000);
    }
    
    infiniteloop()
    .....
    myStartTime = anytime1
    myEndTime = anytime2
    // when change the myStartTime or myEndTime do:
    .....
    
    clearTimeout(timeoutId)
    infiniteloop()
    
    Login or Signup to reply.
  2. Here’s a setRepeating that is subtly different from setInterval. A setInterval call will do something at regular intervals regardless of how long the function itself takes. Whereas this setRepeating 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.

    const setRepeating = (fn, interval) => {
        let timer;
        const scheduleNext = () => {
            timer = setTimeout(() => {
                fn();
                scheduleNext();
            }, interval);
        }
        scheduleNext();
        return () => {
            clearTimeout(timer);
        }
    }
    
    // And here's an example of how to use it:
    // Log the date, then, one second later, do it again.
    cancel = setRepeating(() => console.log(new Date()), 1000);
    
    // as an example, cancel it after 5 seconds
    setTimeout(() => cancel(), 5000);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search