Mozilla scroll advice Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Mozilla scroll advice without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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() {
      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?

mozilla link of scroll


Default browser behavior

On each scroll event (be it 1 pixel or more), the browser will repaint the layout. (for obvious layout purpose)

The performance problem

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.

requestAnimationFrame()’ solution

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.

The idea of ticking

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.

We are here to answer your question about Mozilla scroll advice - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji