Jump to content

Working with setInterval()


davej

Recommended Posts

setTimeout and setInterval both return an id that you can use to reference the time. Save this id "globally" within the context of your script, and only start a new timeout/interval if that variable/id doesn't already exist. and clear it out (set it to null/false/etc) when you stop the slideshow.
I've now tried using window.clearInterval() but I still see some odd results. Can mouse-click events get queued up? You are saying that after I use clearInterval() I should set the var to null and I should not begin a delay unless the var == null. As long as I use different var's I can have different simultaneous delays? http://www.w3schools.com/js/js_timing.asp
Link to comment
Share on other sites

As long as I use different var's I can have different simultaneous delays?
Yes. Each var would represent a separate "thread." If each "thread" calls the same process, or affects the environment in a similar way, then be prepared for that. An interesting fact.
var i = setInterval(someFunc, 1000);i = setInterval(otherFunc, 1000);

You would think that since the second call to setInterval overwrites the value of i, then the first timer would be nullified. Not true. That is because i is not some sort of timer object. It is only a Number, specifically the ID of a "timer object" that the browser tracks internally. The only way to stop a timer initialized by setInterval is by calling clearInterval. If you don't call clearInterval before calling setInterval, you could end up with an arbitrary number of timers all running simultaneously. That could easily happen if you called setInterval in a loop or in response to a user event, like a mouseclick. As to setting the value of a timer ID to null, that would give you an internal check to see if a timer might already be running. When you pass a variable to clearInterval, its value does not change. If you nullify the variable immediately after passing it to clearInterval, then a subsequent process can check the value of the timer ID and know if a timer is in fact running. I would personally be much happier if JavaScript provided an actual Timer object that you could manipulate explicitly. I find the absence of such a thing most conspicuous. jQuery has such stuff, but that's no excuse.

Edited by Deirdre's Dad
Link to comment
Share on other sites

I actually decided to use setTimeout/clearTimeout rather than setInterval/clearInterval but the null check seems to have solved my erratic delay problem. Thanks.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...