Skip to content

Instantly share code, notes, and snippets.

@rohozhnikoff
Created November 11, 2019 01:07
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 rohozhnikoff/59099d857dcac67e624fe383e684b19d to your computer and use it in GitHub Desktop.
Save rohozhnikoff/59099d857dcac67e624fe383e684b19d to your computer and use it in GitHub Desktop.
var $$timeoutId = 0;
const deferreds = {};
function $timeout(fn, delay) {
const timeoutId = $$timeoutId++;
let cachedReject;
const reject = (e) => cachedReject(e);
const promise = new Promise((resolve, reject) => {
cachedReject = reject;
setTimeout(() => {
try {
resolve(fn());
} catch (e) {
reject(e);
} finally {
delete deferreds[timeoutId];
}
}, delay);
});
promise.reject = reject;
promise.$$timeoutId = timeoutId;
deferreds[timeoutId] = promise;
return promise;
}
$timeout.cancel = (promise) => {
if (!promise) return false;
if (!promise.hasOwnProperty("$$timeoutId")) {
throw new Error(
"`$timeout.cancel()` called with a promise that was not generated by `$timeout()`."
);
}
if (!deferreds.hasOwnProperty(promise.$$timeoutId)) return false;
var id = promise.$$timeoutId;
var deferred = deferreds[id];
deferred.reject("canceled");
delete deferreds[id];
return Promise.reject(id);
};
export default $timeout;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment