blob: c8c9dfddf60d270459b29e460979be6819e8b856 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
'use strict';
export default function timeout(asyncFn, miliseconds) {
var originalCallback, timer;
var timedOut = false;
function injectedCallback() {
if (!timedOut) {
originalCallback.apply(null, arguments);
clearTimeout(timer);
}
}
function timeoutCallback() {
var error = new Error('Callback function timed out.');
error.code = 'ETIMEDOUT';
timedOut = true;
originalCallback(error);
}
function injectCallback(asyncFnArgs) {
// replace callback in asyncFn args
var args = Array.prototype.slice.call(asyncFnArgs, 0);
originalCallback = args[args.length - 1];
args[args.length - 1] = injectedCallback;
return args;
}
function wrappedFn() {
// setup timer and call original function
timer = setTimeout(timeoutCallback, miliseconds);
asyncFn.apply(null, injectCallback(arguments));
}
return wrappedFn;
}
|