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:
var to;
function f1() {
// Kill other running instances of all functions
to = setTimeout(() => {
document.getElementById("result").innerHTML = "1st function";
}, 10000 * Math.random());
}
f2 and f3 are basically the same, but prints different outputs after the less-than-10-second pause.
However, if the user clicks b1 and then immediately click b2, there is a possibility that the innerHTML within f1 gets run after that in f2, and the output would be 1st function, instead of 2nd function.
What I want is to implement, at the start of each function, a statement that kills/ignores/bypasses all functions 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?