Created
November 11, 2019 01:07
-
-
Save rohozhnikoff/59099d857dcac67e624fe383e684b19d to your computer and use it in GitHub Desktop.
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
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