The following Javascript code works in all browsers except IE9. What’s the fix?
setTimeout('doSomething();clearTimeout();',500);
The debugger says that it’s expecting me to pass an ID number to clearTimeout(), when all I’m doing is clearing all timeouts.
As others have said,
clearTimeout()without any arguments doesn’t do anything.clearTimeout()requires you to specify which timeout you want to clear. This applies in all browsers. Maybe only IE is reporting the error, but it’s causing a problem in all of them.Perhaps the reason you’re calling
clearTimeout()is that you think thesetTimeout()needs to be cleared in case it keeps getting called? This is incorrect —setTimeout()causes its code to be called just once, after the given amount of time.Therefore, since you’re trying to clear the timeout after it’s already been triggered, there’s nothing to clear anyway.
There is a separate command called
setInterval()which does trigger a repeating timeout. This would need to be cleared to stop it calling over and over and over, but it’s generally considered to be a bad idea to usesetInterval()anyway, so I won’t dwell on it too much here.The other thing you should do is avoid calling
setIntervalwith a string parameter. Just specify the function you want to call directly, instead.In short, your code should look like this:
That should be sufficient for your example to work fine in all browsers.
As I said, you don’t need to clear the timeout in your case, but in case you do need to clear it in another instance, you would need to have
setTimeout(orsetInterval) return a value. This value is a reference object to the timer, and this reference is what you need to pass intoclearTimeout.ie:
Hope that helps clear things up.