This is an extension of my previous question, mainly out of curiosity: Kill all running JavaScript functions with Timeouts on click
I have a webpage with 3 buttons and a "result" section:
<button id="b1" onclick="f1()">1st button</button>
<button id="b2" onclick="f2()">2nd button</button>
<button id="b3" onclick="f3()">3rd button</button>
<p id="result">"Here will be the result!"</p>
Here are the snippets for the JavaScript functions. I also utilized web worker:
// The functions are similar, but the outputs are different
var worker;
function calcF1() {
var answer;
for (let i = 0; i < 1e9; i++) {
// Do some complicated calculations
}
postMessage(answer);
}
function f1() {
// TODO: Kill other running instances of all functions
// Calling worker
var cf1 = calcF1.toString();
var code = cf1.substring(cf1.indexOf('{')+1, cf1.lastIndexOf('}'));
var blob = new Blob([code], {type: 'application/javascript'});
worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = message => {
document.getElementById("result").innerHTML = "1st function";
};
}
function calcF2() {
var answer;
for (let i = 0; i < 1e9; i++) {
// Do some complicated calculations
}
postMessage(answer);
}
function f2() {
// TODO: Kill other running instances of all functions
// Calling worker
var cf2 = calcF2.toString();
var code = cf2.substring(cf2.indexOf('{')+1, cf2.lastIndexOf('}'));
var blob = new Blob([code], {type: 'application/javascript'});
worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = message => {
document.getElementById("result").innerHTML = "2nd function";
};
}
function calcF3() {
var answer;
for (let i = 0; i < 1e9; i++) {
// Do some complicated calculations
}
postMessage(answer);
}
function f3() {
// TODO: Kill other running instances of all functions
// Calling worker
var cf3 = calcF3.toString();
var code = cf3.substring(cf3.indexOf('{')+1, cf3.lastIndexOf('}'));
var blob = new Blob([code], {type: 'application/javascript'});
worker = new Worker(URL.createObjectURL(blob));
worker.onmessage = message => {
document.getElementById("result").innerHTML = "3rd function";
};
}
However, if the user clicks b1 and then immediately click b2, the worker by f1 will not terminate and keep running. If worker from f1 finishes before that from f2 does, then result will show 1st function and then replaced by 2nd function. There's also a possibility that the worker by f2 finishes first, in which case result would show 2nd function and then be replaced by 1st function.
What I want is to implement, at the start of each function, a statement that kills/ignores/bypasses all functions and/or all web workers that are currently running so that the final output would always be the one associated with the last button the user pressed. How can it be best implemented?
EDIT: Thanks for pointing out the web worker. My original implementations involved web workers but I forgot to mention. The question has been updated.
setTimeout(), which seem to be easier to kill. @RuChernChong