3 ms·
I use a generic version of the waiting-for-pause trick: // execute callback only after a pause in user input; the function returned // can be used to h
by dionidium 16y ago
I use a generic version of the waiting-for-pause trick:
// execute callback only after a pause in user input; the function returned
// can be used to handle an event type that tightly repeats (such as typing
// or scrolling events); it will execute the callback only if the given timout
// period has passed since the last time the same event fired
function createOnPause(callback, timeout, _this) {
return function(e) {
var _that = this;
if (arguments.callee.timer)
clearTimeout(arguments.callee.timer);
arguments.callee.timer = setTimeout(function() {
callback.call(_this || _that, e);
}, timeout);
}
}
Use it like this:
document.addEventListener('scroll', createOnPause(function(e) {
// do something interesting here
}, 1500, this), false);
Edit: Oops! The version in the article runs some code if any scroll event occurred since it last fired, but this one doesn't execute the callback until the user stops scrolling for some amount of time. Anyway, maybe it's still useful for some folks.
- mcav 16y agoI've used that idiom too. It's a great trick. One potential issue is that if you continuously trigger the scroll/resize event, your callback will go an extended time without firing. That's usually only a problem if you're using it to adjust UI elements on scroll/resize, in which case you'd want to add a timer to force the callback if the delay has been too long despite the event still firing often.
- long 16y agoFor anyone that's interested, two related techniques are called "throttling" and "debouncing".
- ryankirkman 16y agoBoth of which are available in the awesome Underscore.js library: http://documentcloud.github.com/underscore/ http://documentcloud.github.com/underscore/