2
votes

how would you guys reinitiate a javascript timer after it's been stopped. Basically I need the timer to stop, and then start again on rollout of a div. I have

var timer = setInterval(myFunction, 1000);
timer

function myFunction(){<br/>
    if(){
        do this
    }
    else if () {
       do this
    }
};

then I have

$("td").hover(
    function () {
        window.clearInterval()
    },<br/>
    function () {
        timer
    }
);

all works good except it doesn't start again on hover off. If I put a new timer in hover off the timer starts to speed up every time you hover on and off.... Any ideas. Thanks

1

1 Answers

3
votes
var intervalID = setInterval(myFunction, 1000);

function myFunction(){
    //logic goes here
};


$("td").hover( function () {
    window.clearInterval(intervalID)
    },
    function () {
    intervalID = setInterval(myFunction, 1000);
} );

Explanation: What's happening is that the setInterval is returning the ID associated with that interval.

I did a littse jsFiddle to show it works.

NOTE: this doesn't pause the current Interval. It stops it and starts it again. So if you were in a 10sec interval at 9 secs and stopped it. When it starts again it will take another 10secs.