mithril-vndb/api/throttle.js
Pat Cavit 04eaa25ab1 Support for skipping redraws (#1049)
Mostly useful for event handlers, setting `e.redraw = false` will prevent mithril from re-rendering.
2016-05-20 11:50:41 -07:00

23 lines
691 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()
if (typeof synchronous === "object" && "redraw" in synchronous && !synchronous.redraw) return
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))
}
}
}