re: Why not to use setInterval VIEW POST

VIEW FULL DISCUSSION
 

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...

 
 
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!

 

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);

code of conduct - report abuse