ClearInterval on hover - resume on mouseLeave[Solved]

I have the the block of code below that clears the interval(pauses) when you hover the targeted box but doesn’t resume on mouseLeave. I’ve tried all I can but can’t figure out what the problem is. Any ideas what the problem could be?

$(function () {        
        
            if ($('.alert-box').length > 1) {
     var timer =  setInterval(function () {    
            if ($(".alert-box:visible").next().length != 0)
            $(".alert-box:visible").next().show().prev().hide();
        else {
            $(".alert-box:visible").hide();
            $(".alert-box:first").show();
        }
        return false;
    
        }, 6000);
    }
    $('.alert-box').hover(function (ev) {
    clearInterval(timer);
},function (ev) {
    setInterval(timer);
  
  });

    })

;

Should setInterval have a delay number?

Paul you can find it just below “return false”

setInterval returns an integer (line 4), but you’re trying to pass it as a function (line 19). You’re actually going to need 2 variables for this, one to store the function and another to store the ID. Here’s one way:

$(function () {        
    // The reusable timer callback
    var timer = function(){
        if ($(".alert-box:visible").next().length != 0)
            $(".alert-box:visible").next().show().prev().hide();
        else {
            $(".alert-box:visible").hide();
            $(".alert-box:first").show();
        }
        // return false; // This isn't necessary
    }
    // The timer ID
    var timerID = null

    // Run on load if this thing is set
    if ($('.alert-box').length > 1) {
        timerID =  setInterval(timer, 6000);
    }

    // Toggle the timer
    $('.alert-box').hover(function (ev) {
        clearInterval(timerID);
    // - Notice how we pass a function and get an integer
    },function (ev) {
        timerID = setInterval(timer, 6000);
    });
})
1 Like

Yes, that’s for when you’re initially setting up the setInterval, but once it’s removed and on mouseLeave you want to set it up again, that’s where you also need to set up the delay for setInterval.

I’ll leave you with @labofoz

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.