Skip to content

Commit 3c1a1bb

Browse files
authored
Merge pull request #492 from jessetan/raf-scroll
Debounce scroll and resize through rAF
2 parents e25871d + 64ddc8f commit 3c1a1bb

File tree

1 file changed

+39
-4
lines changed

1 file changed

+39
-4
lines changed

js/theme.js

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,21 @@ function ThemeNav () {
2929
// Set scroll monitor
3030
self.win.on('scroll', function () {
3131
if (!self.linkScroll) {
32-
self.winScroll = true;
32+
if (!self.winScroll) {
33+
self.winScroll = true;
34+
requestAnimationFrame(function() { self.onScroll(); });
35+
}
3336
}
3437
});
35-
setInterval(function () { if (self.winScroll) self.onScroll(); }, 25);
3638

3739
// Set resize monitor
3840
self.win.on('resize', function () {
39-
self.winResize = true;
41+
if (!self.winResize) {
42+
self.winResize = true;
43+
requestAnimationFrame(function() { self.onResize(); });
44+
}
4045
});
41-
setInterval(function () { if (self.winResize) self.onResize(); }, 25);
46+
4247
self.onResize();
4348
});
4449
};
@@ -166,3 +171,33 @@ module.exports.ThemeNav = ThemeNav();
166171
if (typeof(window) != 'undefined') {
167172
window.SphinxRtdTheme = { StickyNav: module.exports.ThemeNav };
168173
}
174+
175+
176+
// requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel
177+
// https://gist.github.com/paulirish/1579671
178+
// MIT license
179+
180+
(function() {
181+
var lastTime = 0;
182+
var vendors = ['ms', 'moz', 'webkit', 'o'];
183+
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
184+
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
185+
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
186+
|| window[vendors[x]+'CancelRequestAnimationFrame'];
187+
}
188+
189+
if (!window.requestAnimationFrame)
190+
window.requestAnimationFrame = function(callback, element) {
191+
var currTime = new Date().getTime();
192+
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
193+
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
194+
timeToCall);
195+
lastTime = currTime + timeToCall;
196+
return id;
197+
};
198+
199+
if (!window.cancelAnimationFrame)
200+
window.cancelAnimationFrame = function(id) {
201+
clearTimeout(id);
202+
};
203+
}());

0 commit comments

Comments
 (0)