Last active
December 23, 2016 17:38
-
-
Save kevinweber/f14b15e0954140a93aa28b7c6d422b2f to your computer and use it in GitHub Desktop.
Throttle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Throttle function | |
* based on https://remysharp.com/2010/07/21/throttling-function-calls | |
*/ | |
function throttle(fn, threshold, scope) { | |
threshold = threshold || 250; | |
var last, | |
deferTimer; | |
return function () { | |
var context = scope || this, | |
now = +new Date(), | |
args = arguments; | |
if (last && now < last + threshold) { | |
clearTimeout(deferTimer); | |
deferTimer = setTimeout(function () { | |
last = now; | |
fn.apply(context, args); | |
}, threshold); | |
} else { | |
last = now; | |
fn.apply(context, args); | |
} | |
}; | |
} | |
// Use it like this ... | |
$('body').on('mousemove', throttle(function (event) { | |
console.log('tick'); | |
}, 1000)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Throttle function from Mozilla using requestAnimationFrame & customEvent | |
* Source: https://developer.mozilla.org/en-US/docs/Web/Events/resize | |
*/ | |
(function () { | |
var throttle = function (type, name, obj) { | |
obj = obj || window; | |
var running = false; | |
var func = function () { | |
if (running) { | |
return; | |
} | |
running = true; | |
requestAnimationFrame(function () { | |
obj.dispatchEvent(new CustomEvent(name)); | |
running = false; | |
}); | |
}; | |
obj.addEventListener(type, func); | |
}; | |
throttle("resize", "optimizedResize"); | |
throttle("orientationchange", "optimizedOrientationchange"); | |
})(); | |
// Use it like this ... | |
window.addEventListener(eventName, function () { | |
myFunction(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment