-
Notifications
You must be signed in to change notification settings - Fork 1
/
when.js
52 lines (41 loc) · 1.42 KB
/
when.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
// the require('setImmediate') adds a setImmediate polyfill to the global
// scope. (this is for backwards and browser compatibility)
require('setimmediate');
function when(condition, code){
// set immediate to a blank function, I don't want to push the first
// check condition to a back of a queue
var immediate = setImmediate(function(){});
checkCondition(); //do a check straight away.
function checkCondition(){
if(condition()){
clear(); //there might be nothing to clear, but theres no harm calling it.
code(); //if the condition is true, run the code striaght away.
// in previous releases, I pushed the code() to the back of the io queue again with a setImmediate,
// but there is no point in doing that, making the program wait longer to execute something
// which might change the state to fire another when function.
} else {
immediate = setImmediate(checkCondition);
}
}
function clear(){
clearImmediate(immediate);
}
function reset(){
clear();
immediate = setImmediate(function(){});
checkCondition();
}
function setCondition(newCondition){
condition = newCondition;
}
function setCode(newCode){
code = newCode;
}
return {
'clear': clear,
'reset': reset,
'setCondition': setCondition,
'setCode': setCode
};
};
module.exports = exports = when;