I have a recursive type function in Javascript that runs like this:
function loadThumb(thumb) {
rotate=setTimeout(function() {
loadThumb(next);
}, delay);
}
Note: I've simplified the function to make it easier to read.
I have "a" tags called like this
<a href="#" onclick="loadThumb(3); clearTimeout(rotate);">Load thumb 3</a>
However, they don't clearout the timer, the timer continues to cycle through the function irregardless of the clearTimeout()
being called.
Any ideas why? I think it might have something to do with a scope problem or something like that.
This will be the ID that was returned by the setTimeout() function. You can clear the timeout by using this id which identifies the timeout. The ids which will be sent as a parameter to this function are being shared by two functions setTimeout() and setInterval().
To clear or cancel a timer, you call the clearTimeout(); method, passing in the timer object that you created into clearTimeout(). For example, the code below shows how to properly clear a timer inside of a functional React component. const App = () => { useEffect(() => { const timer = setTimeout(() => console.
How to Stop the Execution? The clearTimeout() method stops the execution of the function specified in setTimeout(). The window.clearTimeout() method can be written without the window prefix.
The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.
Yeah, you need to make rotate a global variable. Simply declare it outside the function like so:
var rotate;
var delay = 1000;
function loadThumb(thumb) {
alert("loading thumb: " + thumb);
rotate = setTimeout(function() {
loadThumb(thumb + 1);
}, delay);
}
Also, you need to make sure you clear the timeout before you call loadThumb
. Otherwise you'll clear the timer you just started.
<a href="#" onclick="clearTimeout(rotate); loadThumb(3);">Load thumb 3</a>
fiddle: http://jsfiddle.net/63FUD/
it may be the issue of scope so make rotate as global variable and call clearTimeout(rotate);
refer clearTimeout() example
It may be a scoping issue if you are not declaring rotate
externally.
Try this:
var rotate = 0;
function loadThumb(thumb) {
rotate=setTimeout(function() {
loadThumb(next);
}, delay);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With