Skip to content

Instantly share code, notes, and snippets.

@tobx
Created December 27, 2021 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobx/bf2a63e23837927da3696c0c881be666 to your computer and use it in GitHub Desktop.
Save tobx/bf2a63e23837927da3696c0c881be666 to your computer and use it in GitHub Desktop.
Async version of setTimeout
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