Problem with setInterval (); and clearInterval

I have a problem with setinterval. It is probably best to show an example, here is the link:

http://boudaki.com/testing/carouselTest

I basically have problems creating this work, as if I needed it. When the page loads, the contents rotate every three seconds, as well as the number buttons on the right, too. when you click on the button, the buttons expand and the animation stops - all is well. Then, when you click the small close button at the bottom of the buttons, the animation resumes - everything is fine ... but then when you click on the numbered buttons again, the animation continues to move. Why?

There is quite a bit of code here, but setIntervals and clear intervals:

  • line 69: on document.ready run the animation off -assign timerId for global var
  • line 87: When the user clicks on the numbered clearinterval button in this animation
  • line 102: when the user presses the close button, start the animation again

What is it .... I just don’t understand why this does not stop the animation a second time ??? Can anyone understand why?

Any ideas?

+4
source share
4 answers

$ closeButton.click (function () {...}); located inside your loop. This handler is added 4 times, so when you click close, 4 timers are added and only 1 is cleared when you open the menu again.

+1
source

This is an assumption, but try to cast all your functions and variables into a call to $(document).ready(function() {...}) .

Then change your setInterval() so that you pass the function reference instead of the string for eval:

 timerId = setInterval( rotateForward, 3000 ); 

Be sure to change them all.

Honestly, I don't know why this worked, but creating a local variable can help ensure that we are dealing with only one version of timerId .

+3
source

I think the problem is determining the scope of timerId. Try changing the alert ("should stop now"); for warning ("should stop now" + timerId);

I bet you will find that timerId is always the same.

+1
source

The only thing I can think of is ... I'm sure you cannot put () inside the setInterval call. It seems to work at first, but maybe this part of the problem? It's hard to say ... but I would at least start there.

 setInterval("rotateForward", 3000); 

Also, try calling clearInterval every time before you start it.

0
source

All Articles