Skip to content

Instantly share code, notes, and snippets.

@kuwabataK
Last active August 17, 2019 05:15
Show Gist options
  • Save kuwabataK/4bcd81f0c14af8ebbdf13249c7eb6a4e to your computer and use it in GitHub Desktop.
Save kuwabataK/4bcd81f0c14af8ebbdf13249c7eb6a4e to your computer and use it in GitHub Desktop.
cancelable Promise setTimeout() sample
function asyncSetTimeout(msec, func = () => {}){
let timeoutId
let r
const exec = () => new Promise((res) => {
r = res
timeoutId = setTimeout(async () => {
timeoutId = null
await func()
res()
},msec)
})
return {
exec,
cancel: () => {
if (timeoutId) {
clearTimeout(timeoutId)
timeoutId = null
r()
}
}
}
}
async function sleep(msec){
return new Promise((res)=>{
setTimeout(()=>res(),msec);
})
}
console.log('start')
const func = async()=>{
console.log('func start!!')
await sleep(1000)
console.log('func finish!!')
}
let cancel
(async ()=>{
const a = asyncSetTimeout(1000,func)
cancel = a.cancel
await a.exec()
console.log('finish')
})()
cancel()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment