clock-interval
Advanced tools
Comparing version 1.0.0 to 1.1.0
21
index.js
module.exports = function clockInterval(fn) { | ||
var second = 1000, | ||
time = second - (Date.now() % second); | ||
var second = 1000, timer; | ||
function interval() { | ||
var time = second - (Date.now() % second); | ||
setTimeout(function() { | ||
fn(); | ||
clockInterval(fn); | ||
}, time); | ||
timer = setTimeout(function timeout() { | ||
fn(); | ||
interval(); | ||
}, time); | ||
} | ||
interval(); | ||
return { | ||
cancel: function cancel() { | ||
clearTimeout(timer); | ||
} | ||
}; | ||
}; |
{ | ||
"name": "clock-interval", | ||
"version": "1.0.0", | ||
"version": "1.1.0", | ||
"description": "A precise interval timer pinned to system clock", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
# perfect-interval | ||
A precise interval timer | ||
A precise interval timer pinned to system clock | ||
## How to use | ||
``` | ||
npm install clock-interval | ||
``` | ||
#### Example usage | ||
Update an element with the currnt time | ||
```js | ||
var clockInterval = require('clock-interval'); | ||
function pad(num) { | ||
return ('0' + num).slice(-2); | ||
} | ||
clockInterval(function() { | ||
var clockEl = document.getElementById('clock'), | ||
dateObj = new Date(); | ||
clockEl.innerHTML = pad(dateObj.getHours()) + ':' + pad(dateObj.getMinutes()) + ':' + pad(dateObj.getSeconds()); | ||
}); | ||
``` | ||
Cancel the interval | ||
```js | ||
var timer = clockInterval(function() {}); | ||
// Cancel the timer | ||
timer.cancel(); | ||
``` | ||
## Why not use setInterval? |
30
test.js
@@ -65,1 +65,31 @@ var test = require('tape'), | ||
}); | ||
test('Cancel works', function(t) { | ||
var fn = sinon.stub(); | ||
var timer = sinon.useFakeTimers(); | ||
// Return 2 different dates | ||
sinon.stub(Date, 'now', (function() { | ||
var count = 0; | ||
return function() { | ||
if (count === 0) { | ||
count++; | ||
return 1438569041176; | ||
} else { | ||
return 1438569042004; | ||
} | ||
} | ||
})()); | ||
var interval = clockInterval(fn); | ||
timer.tick(824); | ||
timer.tick(995); | ||
t.assert(fn.callCount === 1); | ||
interval.cancel(); | ||
timer.tick(1); | ||
t.assert(fn.callCount === 1); | ||
timer.restore(); | ||
t.end(); | ||
}); |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
27164
14
89
34