Вот несколько способов реализации события прокрутки JavaScript с задержкой:
-
Использование функции setTimeout():
let scrollTimeout; window.addEventListener('scroll', function() { clearTimeout(scrollTimeout); scrollTimeout = setTimeout(function() { // Your code to be executed after the scroll delay }, 300); // Adjust the delay time (in milliseconds) as needed }); -
Устранение события прокрутки:
function debounce(func, delay) { let timeoutId; return function() { clearTimeout(timeoutId); timeoutId = setTimeout(func, delay); }; } window.addEventListener('scroll', debounce(function() { // Your code to be executed after the scroll delay }, 300)); // Adjust the delay time (in milliseconds) as needed -
Использование requestAnimationFrame():
let isScrolling = false; function scrollHandler() { // Your code to be executed after the scroll delay isScrolling = false; } window.addEventListener('scroll', function() { if (!isScrolling) { isScrolling = true; requestAnimationFrame(scrollHandler); } }); -
Регулирование события прокрутки:
function throttle(func, limit) { let inThrottle; return function() { const args = arguments; const context = this; if (!inThrottle) { func.apply(context, args); inThrottle = true; setTimeout(function() { inThrottle = false; }, limit); } }; } window.addEventListener('scroll', throttle(function() { // Your code to be executed after the scroll delay }, 300)); // Adjust the delay time (in milliseconds) as needed
Эти методы позволяют добавлять задержку к выполнению кода JavaScript, запускаемого событием прокрутки. Конкретный метод, который вы выберете, зависит от ваших требований и соображений производительности.