tiny jquery way
$.fn.scrollStopped = function(callback) {
var that = this, $this = $(that);
$this.scroll(function(ev) {
clearTimeout($this.data('scrollTimeout'));
$this.data('scrollTimeout', setTimeout(callback.bind(that), 250, ev));
});
};
After 250 ms from the last scroll event, this will invoke the "scrollStopped" callback.
http://jsfiddle.net/wtRrV/256/
lodash (even smaller)
function onScrollStopped(domElement, callback) {
domElement.addEventListener('scroll', _.debounce(callback, 250));
}
http://jsfiddle.net/hotw1o2j/
pure js (technically the smallest)
function onScrollStopped(domElement, callback, timeout = 250) {
domElement.addEventListener('scroll', () => {
clearTimeout(callback.timeout);
callback.timeout = setTimeout(callback, timeout);
});
}
https://jsfiddle.net/kpsxdcv8/15/
strange fact
clearTimeout and clearInterval params don't have to be defined and can even be wrong types or even omitted.
http://jsfiddle.net/2w5zLwvx/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…