Reputation: 5280
Let's take an example (i am not asking how to cancel/kill a setTimeout at all, i just use it to represent different processing times of different tasks):
<div id="content">
</div>
<p>Which color do you prefer ?</p>
<button id="long" onClick="long_process();">Blue</button>
<button id="short" onClick="short_process();">Red</button>
<script>
function long_process() {
setTimeout(function() {
$('div#content').text('My favorite color is blue');
}, 10000);
}
function short_proccess() {
setTimeout(function() {
$('div#content').text('My favorite color is red');
}, 1000);
}
$('button#long').click();
$('button#short').click();
</script>
Regarding this example, you probably know already what i am going to ask, how can we stop the long processing action if the user launch a short processing action which is supposed to take over it ?
In this example, if the favorite color of the user is red, but the user click the wrong (blue) button, then click the red button, the blue color willl be the last color displayed because its process is longer.
I know how to manage it with C/C++ using the pthread library, but i have no idea with javascript, and it's very important in some situation to be 100% sure about what your app will display.
Thanks !
Upvotes: 3
Views: 3602
Reputation: 298176
When creating a timer, setTimeout
and setInterval
return an ID that you can use to reference that timer:
var long_timer;
function long_process() {
long_timer = setTimeout(...);
}
When you want to stop that timer, pass that ID into clearTimeout
or clearInterval
:
if (long_timer) {
clearTimeout(long_timer);
}
Upvotes: 2