Reputation: 123
I need to implement a function in javascript that runs an async process in the next way:
What is the best aproach? A global variable that is accesible for both functions (the async and the UI) or via callbacks?
Upvotes: 0
Views: 620
Reputation: 271
Something that uses events would work just fine.
function main() {
main.running = true
doSomething()
}
function doSomething() {
if (!input.checked) {
console.log("checking")
window.setTimeout(doSomething,1000);
}
else {
main.running = false;
}
}
function changeHandler(event) {
if (event.target.checked == false && main.running == false) {
main();
}
}
var input = document.getElementById('check');
input.onchange=changeHandler;
main.running = false;
<input id="check" type="checkbox">
Upvotes: 1
Reputation: 24191
Without using any external libs etc, a simple way would be using some form of encapsulation that returns you a stop method.
Here is a simple example.
function doAsyncStuff() {
var i = setInterval(function () {
console.log("tick");
}, 1000);
return function stop() {
console.log("Stop called");
clearInterval(i);
}
}
var stop = doAsyncStuff();
document.querySelector("button").onclick = stop;
<button>Stop</button>
You could even extend this to return multiple functions, like resume restart etc.
Upvotes: 2