Cain Nuke Cain Nuke - 6 months ago 30
Javascript Question

Resume a function after clearInterval

I have this code:

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;
});
});


I want to suspend the function on mouseover and resume it on mouse out but I cant get the latter right. How can I resume it?

Thank you.

Answer

There are two ways:

  1. Set a flag that the function being called by the interval checks, and have the function not do anything if it's "suspended."

  2. Start the interval again via a new setInterval call. Note that the old timer value cannot be used for this, you need to pass in the code again.

Example of #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
        }
    });
});

Example of #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
        }
    });
});
Comments