Home › Forums › JavaScript › Your best snippets › Reply To: Your best snippets
December 6, 2016 at 12:55 pm
#248723
Participant
Those are great, thanks for the feedback. :-)
The counter-increment
property is definitely a hidden gem. And those regular expression will turn out to be very handy.
Here’s another nice snippet, for throttling functions – taken from a demo page of Beverley:
function throttle(fn, ms) {
var time, last = 0;
return function() {
var a = arguments, t = this, now = +(new Date),
exe = function() {
last = now;
fn.apply(t, a);
};
clearTimeout(time);
(now >= last + ms) ? exe(): time = setTimeout(exe, ms);
}
}
Usage:
throttle(someFunction, 100)
This will limit the function inside to be executed only once every 100ms. Can be very handy to restrict overenthustiastic code execution based on scroll of resize events for example.
window.addEventListener('resize', throttle(someFunction, 100));
From what I can see, it also includes some code for debouncing. That will make sure the function is executed once more afterwards. Otherwise one might “miss out” on an event that happened 99ms into keeping track…