Last active
August 17, 2019 05:15
-
-
Save kuwabataK/4bcd81f0c14af8ebbdf13249c7eb6a4e to your computer and use it in GitHub Desktop.
cancelable Promise setTimeout() sample
This file contains hidden or 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
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