Why not to use setInterval

Akanksha Sharma on February 19, 2018

Recently, I came across a requirement where I had to call a function repeatedly after specific time interval, like sending ajax call at every 10... [Read Full]
markdown guide
 

How about making an async version of setInterval? Something like...

const setIntervalAsync = (fn, ms) => {
  fn().then(() => {
    setTimeout(() => setIntervalAsync(fn, ms), ms);
  });
};

So we can just do

setIntervalAsync(() => fetch(/* blah */), 3000);

Which would call fetch every 3000ms properly.

P.S. Haven't really tested it, just an idea...

 

And handle errors:

const delayReport = deplayMs => new Promise((resolve) => {
    setTimeout(resolve, deplayMs);
});

setIntervalAsync(async () => {
    try {
        const seed = Math.floor((Math.random() * 100) + 1);
        if (seed % 2 === 0) {
            console.log(new Date());
            await delayReport(500);
        } else { throw new Error('get a random error'); }
    } catch (e) {
        console.error(e);
    }
}, 1000);

 
const delayReport = deplayMs => new Promise((resolve) => {
    setTimeout(resolve, deplayMs);
});

setIntervalAsync(async () => { console.log(new Date()); await delayReport(1000); }, 1000);

The print is

2018-08-26 09:13:43
2018-08-26 09:13:45
2018-08-26 09:13:47
2018-08-26 09:13:49
2018-08-26 09:13:51
2018-08-26 09:13:53

Cool man!

 
 

Another approach is to check that the previous process isn't still running inside the setInterval callback and choose whether to skip that iteration or to kill and restart the timer.

Better would be to trigger actions on user events rather than timed events if that's possible, or to use timers only for pure cosmetics. I don't think setInterval/setTimeout are evil as such, as long as you're careful since suddenly everything's in global scope.

There's a temptation to use them to get out of a fix, though, and I think you're definitely right to treat them as a bit of a smell.

 

Yeah typically I'd expect either a conditional in your response function.

That's also generally how Redux ajax requests are patterned with Redux-Thunk, you would have a conditional in your response handling to verify if it still makes sense to replace the state.

 

As you can see from printed console.log statement that whole load of setInterval events arrive immediately after each other without any delay.

Didn't get a point, as I see from printed console, results are fully predicted. Every single "insideSetInterval" prints with delay of two seconds (like described in setInterval), and also - "returning from server" appears after 4 seconds since first setInterval, which was called with timeout 4000ms, where is "without any delay"?

If you speak about no delay between "returning from server" and "insideSetInterval", of course, because setTimeout with 4sec will wait until interval will be executed twice), and dont have to be in sync with interval prints. With heavy calculation it can load stack, but for simple refreshes - like a timer display update or some other light calculations - working properly, if not forget to handle instance with "clearInterval" when it's no needed anymore.

 

You are right, for light calculations it does not make much of a difference. But for example gmail has to refresh your inbox when new mail arrives, if we were to do it by setTimeInterval, we will queue a lot of requests at server. I have changed the contents of the blog. Please go through that maybe it will put across my point clearly.

 

Thanks for your reply, yes. I agree, if there will be heavy calculation or long time awaiting, it will work unpredictable. For heavy calculations I would like to use some kind of state machines, which will not make additional request if previous one still in pending state (can be timeout of it). Unfortunatelly, we cannot stop executing request to a server, but we can mark it in client side as NOT VALID (throw exception after some timeout), but this will continue execution on server and in case of non-stop requests, they will do DoS attack. But that's also not a setInterval and setTimeout case, there have to be much more code over it, to prevent that kind of issues. If server taking decision when content have to be updated - WebSockets can prevent lot of issues, IMHO they are ready to be used in production.

 

I get what you are trying to say here. A small mistake here though. The timeout in fakeCallToServer should have been a random from 200ms to 15 sec to mimic an actual api response scenario.

code of conduct - report abuse