problem with setInterval(); and clearInterval
I have a problem invo开发者_开发百科lving setinterval. It's probably best to show an example so here's a link here:
http://boudaki.com/testing/carouselTest
Basically I'm having problems making this work like I need it to. When the page loads the content rotates every three seconds and the numbered buttons on the right do so also. when you click on a button the buttons extend and the animation is stopped - all good. Then when you click the little close button at the bottom of the buttons the animation resumes - all good....but then when you come to click on the numbered buttons again the animation keeps on going. Why?
There's rather a lot of code but the setIntervals and clear intervals are:
- line 69: on document.ready start the animation off -assign timerId to a global var
- line 87: When the user clicks on the numbered button clearinterval in that animation
- line 102: when the user clicks on the close button start the animation again
That's it....I just don't get why it doesn't stop the animation the second time around??? Can anyone see why?
Any ideas?
This is a guess, but try bringing all your functions and variables into the $(document).ready(function() {...})
call.
Then change your setInterval()
so that you're passing in a reference to the function instead of a string for eval:
timerId = setInterval( rotateForward, 3000 );
Be sure to change all of them.
To be honest I don't know why this would work, but making the variable local may help to ensure that we're dealing with only one version of timerId
.
$closeButton.click(function() { ... }); is inside of your loop. That handler is getting added 4 times, so when you click close, 4 timers are added and only 1 is cleared when you open the menu again.
I think the problem is the scoping of timerId. Try changing alert('should stop now'); to alert('should stop now' + timerId);
I'll bet you'll find that timerId is always the same value.
The only thing I can think of is... I'm pretty sure you can't put the () inside the setInterval call. It does seem to work at first, but maybe that's part of the issue? Hard to say... but I'd at least start there.
setInterval("rotateForward", 3000);
Also, maybe try calling the clearInterval every time before you start it.
精彩评论