JavaScript / JQuery - 使用后如何暂时禁用功能?

JavaScript / JQuery - How to temporarily disable function after use?

我有一个简单的 JS,只要向上或向下移动鼠标滚轮,它就会平滑地自动滚动到另一个 div。

这是脚本:

    $(document).bind('mousewheel', function(evt) {
        var delta = evt.originalEvent.wheelDelta
        if(delta < 0){
                $('html, body').animate({
                    scrollTop: $("#content-wrapper").offset().top
                }, 3000);
        }
        else {
                $('html, body').animate({
                scrollTop: $("#bgheader").offset().top
                }, 3000);
        }         
    });

我的问题是,如果我用鼠标滚轮玩几秒钟,它就会开始到处滚动,因为记录的每一个动作都会作为额外的脚本启动排队。

有什么办法可以在脚本中添加某种 'cooldown' 吗?这样在使用一次之后就可以再次使用,比方说 3 秒?或者一旦动画完成?

我用过超时。

var maxPoll = 3000,
    eventActive = false;

$(document).bind('mousewheel', function(evt) {
    if(eventActive) { 
        return
    } else {
        setTimeout(maxPoll, function() { eventActive = True })
    }
    var delta = evt.originalEvent.wheelDelta
    if(delta < 0){
        $('html, body').animate({
            scrollTop: $("#content-wrapper").offset().top
        }, maxPoll);
    }
    else {
        $('html, body').animate({
            scrollTop: $("#bgheader").offset().top
        }, maxPoll);
    }         
});

它很粗糙,它使用全局变量,但它基本上会在动画 运行 时关闭你的事件。

可以解绑wheel事件监听器,完成后使用jQuery的.animate()回调函数重新绑定事件监听器,如下所示:

function scrollHandler (event) {
    $(document).off("mousewheel.custom");
    var delta = event.originalEvent.wheelDelta
    if(delta < 0){
        $('html, body').animate({
            scrollTop: $("#content-wrapper").offset().top
        }, 3000, function () {
            // animation callback function
            $(document).on("mousewheel.custom", scrollHandler);
        }));
    }
    else {
        $('html, body').animate({
           scrollTop: $("#bgheader").offset().top
        }, 3000, function () {
          // animation callback function
          $(document).on("mousewheel.custom", scrollHandler);
        });
    }
}

// namespace the event so we can easily .off() it
$(document).on('mousewheel.custom', scrollHandler);