Skip to content

Commit 5a0ec29

Browse files
committed
Adding throttling for scroll event
1 parent 4407114 commit 5a0ec29

File tree

1 file changed

+38
-3
lines changed

1 file changed

+38
-3
lines changed

jquery.scrolldepth.js

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -97,11 +97,46 @@
9797
}
9898

9999
/*
100-
* Scroll Event
100+
* Throttle function borrowed from:
101+
* Underscore.js 1.5.2
102+
* http://underscorejs.org
103+
* (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
104+
* Underscore may be freely distributed under the MIT license.
101105
*/
102106

103-
$window.on('scroll.scrollDepth', function() {
107+
function throttle(func, wait) {
108+
var context, args, result;
109+
var timeout = null;
110+
var previous = 0;
111+
var later = function() {
112+
previous = new Date;
113+
timeout = null;
114+
result = func.apply(context, args);
115+
};
116+
return function() {
117+
var now = new Date;
118+
if (!previous) previous = now;
119+
var remaining = wait - (now - previous);
120+
context = this;
121+
args = arguments;
122+
if (remaining <= 0) {
123+
clearTimeout(timeout);
124+
timeout = null;
125+
previous = now;
126+
result = func.apply(context, args);
127+
} else if (!timeout) {
128+
timeout = setTimeout(later, remaining);
129+
}
130+
return result;
131+
};
132+
}
133+
134+
/*
135+
* Scroll Event
136+
*/
104137

138+
$window.on('scroll.scrollDepth', throttle(function() {
139+
console.log('foo');
105140
/*
106141
* We calculate document and window height on each scroll event to
107142
* account for dynamic DOM changes.
@@ -132,7 +167,7 @@
132167
if (options.percentage) {
133168
checkMarks(marks, scrollDistance, timing);
134169
}
135-
});
170+
}, 500));
136171

137172
};
138173

0 commit comments

Comments
 (0)