forked from kriszyp/promised-io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
delay.js
35 lines (35 loc) · 1002 Bytes
/
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
/*
* Provides time-based promise-returning delay and schedule functions
*/
({define:typeof define!="undefined"?define:function(factory){module.exports=factory(require)}}).
define(function(require){
if (typeof system === "object" && system.engine === "rhino"){
// for rhino
return require("./engines/rhino/delay");
}
var defer = require("./promise").defer,
LazyArray = require("./lazy-array").LazyArray;
// returns a promise that is fulfilled after the given number of milliseconds
function delay(ms){
var deferred = defer();
setTimeout(deferred.resolve, ms);
return deferred.promise;
};
// returns a lazy array that iterates one every given number of milliseconds
delay.schedule = function(ms){
var callbacks = [];
setInterval(function(){
callbacks.forEach(function(callback){
if(callback()){
callbacks.splice(callbacks.indexOf(callback), 1);
}
});
}, ms);
return LazyArray({
some: function(callback){
callbacks.push(callback);
}
});
};
return delay.delay = delay;
});