I need a sticky bar to be visible and fixed after a certain scroll. I was going to use scroll event, then I met Mozilla page which advise to use window.requestAnimationFrame
as the following :
var last_known_scroll_position = 0;
var ticking = false;
function doSomething(scroll_pos) {
// do something with the scroll position
}
window.addEventListener('scroll', function(e) {
last_known_scroll_position = window.scrollY;
if (!ticking) {
window.requestAnimationFrame(function() {
doSomething(last_known_scroll_position);
ticking = false;
});
}
ticking = true;
});
I have a few questions :
1 - What is the logic behind ticking ?
2 - It seems to me that ticking will always be true since if statement doesn't return anything. This will lead to doSomething function will be called only once. I guess I am wrong, what am I missing?
On each scroll event (be it 1 pixel or more), the browser will repaint the layout. (for obvious layout purpose)
Your function doSomething()
may not finish before two triggered scroll events. You can see it as a stack of doSomething
functions because there will be more calls than your execution time can handle.
This function is defined in the window
object by default. It tells the browser to wait the execution of the passed function before repainting the layout.
As you can see, ticking
will only be false
after doSomething()
. It avoids the previous mentioned stack of events
. It avoids executing the code of another scroll event before the function finished and the browser repainted the layout.
It adds performance to your scroll. I asked some days ago a question which illustrates this situation.