在clearInterval之后恢复一个函数

时间:2016-05-23 07:36:58

标签: 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;
    });
});

我想在鼠标悬停时暂停该功能并在鼠标输出时恢复它,但我不能让后者正确。我怎样才能恢复呢?

谢谢。

3 个答案:

答案 0 :(得分:0)

有两种方法:

  1. 设置一个标志,通过间隔检查调用该函数,并且如果它被“暂停”,则该函数不会执行任何操作。

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

  3. #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
            }
        });
    });
    

答案 1 :(得分:0)

查看这些原型:

        //Initializable
        function Initializable(params) {
            this.initialize = function(key, def, private) {
                if (def !== undefined) {
                    (!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
                }
            };
        }

        function PeriodicJobHandler(params) {
            Initializable.call(this, params);
            this.initialize("timeout", 1000, true);
            var getTimeout = function() {
                return params.timeout;
            };
            var jobs = [];

            function Job(params) {
                //expects params.job() function
                Initializable.call(this, params);
                this.initialize("timeout", getTimeout(), true);
                this.initialize("instant", false);
                var intervalID = undefined;

                this.start = function() {
                    if (intervalID !== undefined) {
                        return;
                    }
                    if (this.instant) {
                        params.job(true);
                    }
                    intervalID = setInterval(function() {
                        params.job(false);
                    }, params.timeout);
                };

                this.stop = function() {
                    clearInterval(intervalID);
                    intervalID = undefined;
                };
            }

            this.addJob = function(params) {
                jobs.push(new Job(params));
                return jobs.length - 1;
            };

            this.removeJob = function(index) {
                jobs[index].stop();
                jobs.splice(index, 1);
            };

            this.startJob = function(index) {
                jobs[index].start();
            };

            this.stopJob = function(index) {
                jobs[index].stop();
            };
        }

Initializable简化了成员初始化,而PeriodicJobHandler能够定期管理作业。现在,让我们实际使用它:

var pjh = new PeriodicJobHandler({});
//It will run once/second. If you want to change the interval time, just define the timeout property in the object passed to addJob
var jobIndex = pjh.addJob({
    instant: true,
    job: function() {
        $el.removeClass("current").eq(++c % tot).addClass("current");
    }
});
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) {
            jobIndex.stop();
        }
    });
    $el.mouseout({
        jobIndex.start();
    });
});

答案 2 :(得分:0)

使用Javascript,它非常简单有效。 您可以在setInterval函数中更改间隔。 它检查suspend变量是假还是真,这里suspend变量设置为true,如果调用mouseEnter函数,如果调用mouseLeave函数则设置为false。



    encodeURIComponent(new Buffer([86,63,228,90,223,138,78,142,224,198,114,68,205,42,206,252,233,190,184,160,199,64,124,176,104,189,106,187,103,105,141,45,16,210,219,189,63,56,150,150]))
=> 'V%3F%EF%BF%BDZ%DF%8AN%EF%BF%BD%EF%BF%BD%EF%BF%BDrD%EF%BF%BD*%EF%BF%BD%EF%BF%BD%E9%BE%B8%EF%BF%BD%EF%BF%BD%40%7C%EF%BF%BDh%EF%BF%BDj%EF%BF%BDgi%EF%BF%BD-%10%EF%BF%BD%DB%BD%3F8%EF%BF%BD%EF%BF%BD'

var displayMsg = document.getElementById('msg').innerHTML;
var i = 0;
var suspend = false;
var sequence = setInterval(update, 100);

function update() {
  if (suspend == false) {
    var dispalyedMsg = '';
    dispalyedMsg = displayMsg.substring(i, displayMsg.length);
    dispalyedMsg += '    ';
    dispalyedMsg += displayMsg.substring(0, i);
    document.getElementById('msg').innerHTML = dispalyedMsg;
    i++;
    if (i > displayMsg.length) {
      i = 0;
    }
  }
}
document.getElementById('msg').addEventListener('mouseenter', mouseEnter);
document.getElementById('msg').addEventListener('mouseleave', mouseLeave);

function mouseEnter() {
  suspend = true;
}

function mouseLeave() {
  suspend = false;
}