javascript - 在clearInterval后恢复函数

标签 javascript jquery clearinterval

我有这个代码:

jQuery(function($) { // DOM is ready
    var $el = $("header tr"),
        tot = $el.length,
        c = 0;
    var timer = setInterval(function() {
        $el.removeClass("current").eq(++c % tot).addClass("current");
    }, 3000);
    $el.first().addClass("current");
    $el.on({
        mouseenter: function(e) {
            clearInterval(timer);
        }
    });
    $el.mouseout({
        timer;
    });
});

我想在鼠标悬停时暂停该功能,并在鼠标移出时恢复该功能,但我无法正确执行后者。我怎样才能恢复它?

谢谢。

最佳答案

有两种方法:

  1. 设置一个标志,以指示间隔检查调用的函数,并让该函数在“挂起”时不执行任何操作。

  2. 通过新的 setInterval 调用再次启动间隔。请注意,旧的计时器值不能用于此目的,您需要再次传入代码。

#1 示例:

jQuery(function($) { // DOM is ready
    var $el = $("header tr"),
        tot = $el.length,
        c = 0,
        suspend = false;                       // The flag
    var timer = setInterval(function() {
        if (!suspend) {                        // Check it
            $el.removeClass("current").eq(++c % tot).addClass("current");
        }
    }, 3000);
    $el.first().addClass("current");
    $el.on({
        mouseenter: function(e) {
            suspend = true;                    // Set it
        },
        mouseleave: function(e) {
            suspend = false;                   // Clear it
        }
    });
});

#2 示例:

jQuery(function($) { // DOM is ready
    var $el = $("header tr"),
        tot = $el.length,
        c = 0,
        timer = 0;

    // Move this to a reusable function
    var intervalHandler = function() {
        $el.removeClass("current").eq(++c % tot).addClass("current");
    };

    // Probably best to encapsulate the logic for starting it rather
    // than repeating that logic
    var startInterval = function() {
        timer = setInterval(intervalHandler, 3000);
    };

    // Initial timer
    startInterval();

    $el.first().addClass("current");
    $el.on({
        mouseenter: function(e) {
            clearInterval(timer);              // Stop it
        }
        mouseleave: function(e) {
            startInterval();                   // Start it
        }
    });
});

关于javascript - 在clearInterval后恢复函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37385146/

相关文章:

javascript - 在 underscore.js 微模板中评估数据的不良做法?

javascript - PHP回显纯文本

javascript - 动态添加 span 标签到 <ng-content></ng-content> 内的链接

c# - 从字符串中删除 HTML

javascript - jQuery 选择菜单验证器适用于 FF 和 Chrome,但不适用于 IE

javascript - 将计时器停止为零

Javascript - JQuery -clearInterval/setInterval - iframe循环不会在点击时停止

javascript - 从Redis返回数据仅在第二次有效

javascript - 如何隐藏和显示子菜单?

javascript - 具有参数的函数上的clearTimeout