Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  58] [ 3]  / answers: 1 / hits: 16586  / 11 Years ago, sun, june 9, 2013, 12:00:00

I have several buttons and each calculates some numbers and displays it on screen. Different buttons take differnet amount of time to finish calculation. In my current implementation, if I click on a button and then click on a different button before the first one finishes, the result from the second button is displayed only after the first one finishes. How can I modify this that as soon as I click the second button, it stops the calculation initiated by the first button and continues with its calculation?



HTML



<input type=button value=One onclick=displayNumber(1)>
<input type=button value=Two onclick=displayNumber(2)>
....


JavaScript



function displayNumber(id) {
alert(calculateAwesomeNumber(id));
}


This may be not possbile in JavaScript as it is single-threaded and only one function can be running at any time. Am I correct?


More From » javascript

 Answers
4

You can use WebWorkers.



This will work in a separate thread and allow you to do heavy calculations without intefering with the UI thread.



You can signal the worker to stop.



See here for examples on how to use:

http://www.html5rocks.com/en/tutorials/workers/basics/

https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers



If WebWorkers isn't an option you can use a flag to force the function to stop:



var _stop;

function displayNumber(num) {

_stop = false;

while(!_stop) {
//calc
}

}


And then on button2 click:



<input type=button value=Two onclick=_stop=true;displayNumber(2)>


Instead of a loop you can check _stop after each segment of the calculation is done.



Just note that if the calculation is long and busy you might not get a response of the button until it finishes. You can use setTimout(..., 0) from time to time inside the calculation to allow other events to execute.



How you implement this will depend on the code you use for calculation.



You can break up the calculation for example like this:



function displayNumber(num) {

var forCalculation;

function step1() {
//calc step 1 you have access to forCalculation and num vars here
if (_stop) return;
setTimeout(step2, 0);
}

function step2() {
//calc step 2 you have access to forCalculation and num vars here
if (_stop) return;
setTimeout(step3, 0);
}
function step3() {
//calc step 3 you have access to forCalculation and num vars here
if (_stop) return;
}
step1();
}

[#77730] Friday, June 7, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
andreasn

Total Points: 238
Total Questions: 107
Total Answers: 111

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
;