1

how to stop time() when mouseout event occur?

jsfiddle link:

`<div id="j" style="height:50px; width:50px; background-color:red;">Hello</div`>


$("#j").mouseenter(function(){
    var count = 3;
    var counterIncrement=1;
    setInterval(timer, 1000); 
    function timer() {
        count = count+counterIncrement;
        if (count == 3  ) {
            counterIncrement = +counterIncrement;
        }
         console.log(count);

    }
});

i want to reset timer() function when mouseout even occur again mousein then start which count =3

2 Answers 2

6

You use the same interval in two DIFFERENT functions (event handles), so that you have to declare a global variable. At the very beginning of your script, declare:

var interval;

Assign the interval to this variable in one event handle:

interval = setInterval(.....);

and clear it when needed in another handle:

clearInterval(interval);

This would be it. Because the variable is globally declared, it will be recognized in both function scopes. It works, because the interval object is passed by reference.

Sign up to request clarification or add additional context in comments.

2 Comments

my setInterval in mouseenter event how can clearInterval in mouseout event? Please provide jsfiddle link!
I have edited my answer. Please check it out. Working without jsFiddle ;)
2
  1. Capture the return value of setInterval()
  2. Call clearInterval(the_value_you_returned_earlier)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.