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 !
setTimeoutreplace an action (for example calling a database or whatever you can imagine), the thing is, if A and B interract differently with the same target and A is longer than B (differents actions never get exactly the same time to process), if i want B as result but i launched A just before, how to do it ? (this is exactly my example)return;. This does mean extra ops in the loop -> slower performance. There isn't really such a thing as "threads" in JavaScript, except web workers!.