Dim Panda
Dim Panda

Reputation: 69

Pause a running setInterval function?

I have 4 functions running on setInterval (tscrolls) which just animate a div's top location every couple of seconds as soon as the document is loaded.

var intervalFunctions = [ tScroll1, tScroll2, tScroll3, tScroll4 ];
var intervalTimer = 3000;
window.setInterval(function(){
  intervalFunctions[intervalIndex++ % intervalFunctions.length]();
}, intervalTimer);

Is there a way to pause this on mouseenter or hover?

Upvotes: 1

Views: 2771

Answers (1)

Jon
Jon

Reputation: 437784

The simplest would be to modify your code to reference a variable (here, hold) which is set on mouseover, and cleared on mouseout:

window.setInterval(function(){ 
    if(hold) {
        return;
    }
    intervalFunctions[intervalIndex++ % intervalFunctions.length](); 
}, intervalTimer); 

This approach will get you most of the way, and if you want to achieve specific behavior you can tweak it to taste.

Upvotes: 7

Related Questions