-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (57 loc) · 1.57 KB
/
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
60
61
62
63
64
'use strict';
/**
* Set an alarm that will execute the provided function at the specified time.
*
* ```js
* // 2 seconds from now
* var now = new Date();
* var date = new Date(+now + 2000);
* alarm(date, function() {
* console.log('Hello, world!');
* });
* ```
* @name alarm
* @param {Date} `date` a Date object or a string that can be passed to the Date constructor.
* @param {Function} `fn` Function to execute at the specified time.
* @return {Function} Returns a function that can be called to cancel the alarm.
* @api public
*/
var alarm = function(date, fn) {
if (typeof fn !== 'function') {
throw new Error('expected second argument to be a function');
}
date = new Date(date);
var now = new Date();
var ms = date - now;
var timer = setTimeout(fn, ms);
return function cancel() {
clearTimeout(timer);
};
};
/**
* Set a recurring alarm that will execute the provide function even X milliseconds.
*
* ```js
* var count = 0;
* var cancel = alarm.recurring(1000, function() {
* console.log((count++) + ' BEEP BEEP BEEP!');
* if (count >= 5) {
* cancel();
* }
* });
* ```
* @param {Number} `ms` Number of milliseconds to specify how often to execute the function.
* @param {Function} `fn` Function to execute every X milliseconds.
* @return {Function} Returns a function that may be called to cancel the recurring alarm.
* @api public
*/
alarm.recurring = function(ms, fn) {
var timer = setInterval(fn, ms);
return function cancel() {
clearTimeout(timer);
};
};
/**
* Expose `alarm`
*/
module.exports = alarm;