rename limiter to throttle and refactor

- don't inject raf/setTimeout since we can't really mock them w/ a good degree of timing accuracy anyways

fix some unrelated tests
This commit is contained in:
Leo Horie 2016-05-19 23:24:04 -04:00
parent 2af3aa27c7
commit 977239d207
15 changed files with 813 additions and 353 deletions

23
api/throttle.js Normal file
View file

@ -0,0 +1,23 @@
"use strict"
module.exports = function(callback) {
//60fps translates to 16.6ms, round it down since setTimeout requires int
var time = 16
var last = 0, pending = null
var timeout = typeof requestAnimationFrame === "function" ? requestAnimationFrame : setTimeout
return function(synchronous) {
var now = new Date().getTime()
var diff = now - last
if (synchronous === true || last === 0 || now - last >= time) {
last = now
callback()
}
else if (pending === null) {
pending = timeout(function() {
pending = 0
callback()
last = new Date().getTime()
}, time - (now - last))
}
}
}