forked from matthewmueller/every
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (49 loc) · 851 Bytes
/
index.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
59
/**
* Module Dependencies
*/
try {
var date = require('date');
} catch(e) {
var date = require('date.js');
}
/**
* Expose `every`
*/
module.exports = every;
/**
* Initialize `every`
*
* @param {String} str
* @param {Function} fn
* @api public
*/
function every(str, fn) {
var now = new Date;
var d = date(str);
var offset = d - now;
var until = offset;
if (0 == until) {
throw new Error('did not recognize "' + str + '"');
}
setTimeout(run, until);
function run() {
d = date(str);
if (!fn.length) {
fn();
reset();
} else {
fn(reset);
}
}
function reset() {
if (!offset) return;
now = new Date;
until = d - now;
// if we're already past the time, reset immediately
if (until < 0) {
run();
} else {
setTimeout(run, until);
}
}
}