Best way to stop async process in Javascript

I need to implement a function in javascript that runs an async process in the next way:

  1. The process will run async checking if a variable is set to true
  2. When true, the async process will stop
  3. When the variables is set to false, the async process will start again.

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

Answers (2)

Mohammed Ilyass NASR
Mohammed Ilyass NASR

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

Keith
Keith

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

Related Questions