JavaScript事件处理滚动事件延迟 [英] JavaScript event handling scroll event with a delay

查看:282
本文介绍了JavaScript事件处理滚动事件延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释并帮助我。我的网页很烂,因为滚动功能正在拖动它。我需要添加延迟,但不明白如何做到这一点。

  $(window).scroll(handleScroll); 


解决方案

你可以写一个简单的 节气门去抖动功能限制每秒滚动事件的次数处理。

  function debounce(method,delay){
clearTimeout(method._tId);
method._tId = setTimeout(function(){
method();
},delay);
}

$(window).scroll(function(){
debounce(handleScroll,100);
});

这将确保每次调用 handleScroll (或换句话说,它每秒钟最多叫10次)。






作为zzzzBov指出Zakas所说的节流功能实际上是一个去抖功能。不同之处在于,去抖动会丢弃多余的滚动事件,而节气门功能应将其排队,以便稍后处理(但以给定的最大速率)。



在这种情况下的滚动事件,你不想要真正的节流。


Can someone explaine and help me with this. My webpage is slugish because the scroll function is dragging it down. I need to add a delay but don't understand how to do this.

$(window).scroll(handleScroll);

解决方案

You could write a simple throttle debounce function to limit the times per second the scroll event will be handled.

function debounce(method, delay) {
    clearTimeout(method._tId);
    method._tId= setTimeout(function(){
        method();
    }, delay);
}

$(window).scroll(function() {
    debounce(handleScroll, 100);
});

This will make sure there's at least 100ms between each call to handleScroll (or, in other words, it's called at most 10 times per second).


As zzzzBov pointed out, what Zakas describes as a throttle function is actually a debounce function. The difference is that debounce discards the superfluous scroll events, while a throttle function should queue them up to be handled later (but at a given maximum rate).

In the case of scroll events, you don't want real throttling.

这篇关于JavaScript事件处理滚动事件延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆