Skip to content

Instantly share code, notes, and snippets.

@johnsonjo4531
Created July 28, 2018 04:13
Show Gist options
  • Save johnsonjo4531/d64a529bb23b755007f9bb650e7768b4 to your computer and use it in GitHub Desktop.
Save johnsonjo4531/d64a529bb23b755007f9bb650e7768b4 to your computer and use it in GitHub Desktop.
Useful promisified timeout with cancellation
module.exports.timeout = function timeout(ms, clear = () => {}) {
return new Promise((res, rej) => {
var t = setTimeout(res, ms);
clear(function cancel () {
clearTimeout(t);
rej("CANCELLED BY TIMEOUT");
});
});
};
var { timeout } = require("./timeout");
// scenario 1: regular timeout
(async () => {
await timeout(1000);
console.log("scenario 1 done");
})();
// scenario 2: cancellation
(async () => {
let passed = true;
try {
await timeout(1000, async function(cancel) {
await timeout(500);
cancel();
});
passed = false;
} catch (err) {
// ignore error
}
if (passed) {
console.log("scenario 2 passed");
} else {
console.log("scenario 2 failed");
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment