forked from cujojs/when
-
Notifications
You must be signed in to change notification settings - Fork 0
/
delay.js
60 lines (51 loc) · 1.42 KB
/
delay.js
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/** @license MIT License (c) copyright 2011-2013 original author or authors */
/**
* delay.js
*
* Helper that returns a promise that resolves after a delay.
*
* @author Brian Cavalier
* @author John Hann
*/
(function(define) {
define(function(require) {
/*global setTimeout*/
var when, setTimer, cjsRequire, vertxSetTimer;
when = require('./when');
cjsRequire = require;
try {
vertxSetTimer = cjsRequire('vertx').setTimer;
setTimer = function (f, ms) { return vertxSetTimer(ms, f); };
} catch(e) {
setTimer = setTimeout;
}
/**
* Creates a new promise that will resolve after a msec delay. If
* value is supplied, the delay will start *after* the supplied
* value is resolved.
*
* @param {number} msec delay in milliseconds
* @param {*|Promise?} value any promise or value after which
* the delay will start
* @returns {Promise} promise that is equivalent to value, only delayed
* by msec
*/
return function delay(msec, value) {
// Support reversed, deprecated argument ordering
if(typeof value === 'number') {
var tmp = value;
value = msec;
msec = tmp;
}
return when.promise(function(resolve, reject, notify) {
when(value, function(val) {
setTimer(function() {
resolve(val);
}, msec);
},
reject, notify);
});
};
});
})(
typeof define === 'function' && define.amd ? define : function (factory) { module.exports = factory(require); });