I'm trying to create the best scroll experience for my users.I'm creating sticky element when the user scrolls down the page - among other things. I'm using the IntersectionObserver API to detect when the element is in the viewport.
But one thing I'm unsure of.How should I handle scroll events in the most optimal way?
Should I use a debounce
function like this:
const debounce = (func, wait, immediate) => { let timeout; return function () { let context = this, args = arguments; let later = () => { timeout = null; if (!immediate) func.apply(context, args); }; let callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); };}window.addEventListener('scroll', debounce(() => { // Run function}, 150));
Or should I use passive: true
like this:
window.addEventListener('scroll', () => { // Run function}, { passive: true});
Or a combination?