简体   繁体   中英

Scroll throttle how to choose a good amount for miliseconds?

I am throttling a scroll event like so:

window.addEventListener('scroll', throttle(() => {
    console.log('scroll event triggered with throttle');
}, 150));

Because I do not want the scroll event to trigger 100's of times per second when somebody scrolls I have throttled it with a lodash throttle function.

I have read up on numerous articles which talk about doing this for obvious performance reasons but none talk about what kind of amount to set for the milliseconds on the throttle.

Of course this might depend on the use case and what code actually gets executed within the throttle. In my case I am doing a viewport check to see if something is still within the viewport.

How would you try and find a suitable amount for the milliseconds? Of course I would love to go as low as possible because it will fire an AJAX requests faster when it comes to an infinite scroll but I also do not want to cause performance issues.

It is hard testing this on a high-end desktop because I will probably never run into performance issues.

A pretty broad question but I would love to know (preferably in chrome) if this can be profiled for worst case scenarios.

I your case I suggest you to use IntersectionObserver . There still will be performance considerations, but if you only want to check that content is visible, it is relatively fast operation - observer will give you this information on IntersectionObserverEntry .

When doing some animations, try to target your animations frame rate of 60fps (one frame per 16ms) and use. If you want to handle orientation change or resize, I'd suggest delay of 450ms (empirically counted duration of orientation change on iPad which in our experiments was largest value of all devices tested).

As for testing, chromium based browsers allow you to throttle CPU: 在此处输入图片说明

I'm not sure if it is available in other browsers.

In any case it might be a good idea to postpone code execution with requestAnumationFrame (for animations) or requestIdleCallback (for computations). It will help to avoid bottlenecks to some degree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM