Created
December 27, 2021 13:53
-
-
Save tobx/bf2a63e23837927da3696c0c881be666 to your computer and use it in GitHub Desktop.
Async version of setTimeout
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
export class Timeout { | |
constructor() { | |
this.timeoutId = 0; | |
} | |
clear() { | |
window.clearTimeout(this.timeoutId); | |
this.timeoutId = 0; | |
} | |
isSet() { | |
return this.timeoutId > 0; | |
} | |
async set(delay) { | |
return new Promise((resolve) => { | |
this.timeoutId = window.setTimeout(() => { | |
this.timeoutId = 0; | |
resolve(); | |
}, delay); | |
}); | |
} | |
} | |
async function test() { | |
const timeout = new Timeout(); | |
const printDelayed = async (message, delay) => { | |
await timeout.set(delay); | |
console.log(message); | |
}; | |
printDelayed( | |
"This does not print, because the timeout will be cleared before.", | |
1000 | |
); | |
console.log("Timeout is set: " + timeout.isSet()); | |
timeout.clear(); | |
console.log("Timeout is set: " + timeout.isSet()); | |
await printDelayed("This prints after one second.", 1000); | |
} | |
test(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment