forked from cujojs/when
-
Notifications
You must be signed in to change notification settings - Fork 0
/
delay.js
59 lines (51 loc) · 1.63 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
/** @license MIT License (c) copyright B Cavalier & J Hann */
/**
* delay.js
*
* Helper that returns a promise that resolves after a delay.
*
* @author [email protected]
*/
(function(define) {
define(['./when'], function(when) {
var undef;
/**
* Creates a new promise that will resolve after a msec delay. If promise
* is supplied, the delay will start *after* the supplied promise is resolved.
*
* Usage:
* // Do something after 1 second, similar to using setTimeout
* delay(1000).then(doSomething);
* // or
* when(delay(1000), doSomething);
*
* // Do something 1 second after triggeringPromise resolves
* delay(triggeringPromise, 1000).then(doSomething, handleRejection);
* // or
* when(delay(triggeringPromise, 1000), doSomething, handleRejection);
*
* @param [promise] anything - any promise or value after which the delay will start
* @param msec {Number} delay in milliseconds
*/
return function delay(promise, msec) {
if(arguments.length < 2) {
msec = promise >>> 0;
promise = undef;
}
return when(promise, function(val) {
var deferred = when.defer();
setTimeout(function() {
deferred.resolve(val);
}, msec);
return deferred.promise;
});
};
});
})(typeof define == 'function'
? define
: function (deps, factory) { typeof module != 'undefined'
? (module.exports = factory(require('./when')))
: (this.when_delay = factory(this.when));
}
// Boilerplate for AMD, Node, and browser global
);