mithril-vndb/api/throttle.js
Leo Horie 977239d207 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
2016-05-19 23:24:04 -04:00

23 lines
620 B
JavaScript

"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))
}
}
}