Skip to content

Instantly share code, notes, and snippets.

@d0peCode
Created August 17, 2019 17:49
Show Gist options
  • Save d0peCode/cc8d306a7b9561a57f6d1696f2a111aa to your computer and use it in GitHub Desktop.
Save d0peCode/cc8d306a7b9561a57f6d1696f2a111aa to your computer and use it in GitHub Desktop.
const sleep = require('./utilities/sleep');
const mySetInterval = (callback, ms, ...args) => {
let token = {
cancelled: false
};
let id = setInterval((...args) => {
callback(token, ...args);
}, ms, ...args);
return function cancel() {
clearInterval(id);
token.cancelled = true;
}
}
const intervalFoo = () => {
let cancel = null;
const checkE2Interval = async(token) => {
if (cancel) {
console.log('cancel true', cancel)
cancel();
}
console.log('interval async');
await sleep(120); //some long action
// If you had more logic here, you could short-circuit it by checking token.cancelled
return cancel = token.cancelled ? null : mySetInterval(checkE2Interval, 100);
};
return cancel = setInterval(checkE2Interval, 100); //returning id
};
module.exports = intervalFoo;
(() => {
const cancellers = [];
cancellers.push(require('./asyncInterval')());
setTimeout(() => {
cancellers.forEach(foo => {
console.log(foo)//not actually cancelling yet
});
}, 1200)
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment