Created
August 17, 2019 17:49
-
-
Save d0peCode/cc8d306a7b9561a57f6d1696f2a111aa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(() => { | |
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