1

What I want to do is stop a function running from ANOTHER function (in JavaScript). here is an example of what I would like to do:

async function process1(){ //this is a normal function running
     //here is a long list of instruction that can take some time (~ 30s)
}

function STOPprocess1(){
  process1().Stop; //this is pseudoCode !
}

When I call STOPprocess1() , I want the process1 function to stop running.

Bojack
  • 111
  • 1
  • 1
  • 8
  • 3
    `while(true)` might break your browser or whatever you're using. You can use `setInterval()` instead and use `clearInterval()` to stop the process. – Yousername Dec 26 '19 at 19:13
  • Except Javascript is a single-threaded language and there is no `sleep`, and `while(true)` is an incredibly terrible idea. What you could do is make sure that whenever functions that should be stoppable _start_, the register a custom `stop` function to some global "stop functions, tied to the function name" manager. Which you'll have to write yourself. – Mike 'Pomax' Kamermans Dec 26 '19 at 19:15
  • Write the `slieep` function such that it checks a variable to see if it should continue sleeping. Set that variable to false in your "stop process" function. – Heretic Monkey Dec 26 '19 at 19:16
  • Does this answer your question? [Stop Javascript Function execution from another Function](https://stackoverflow.com/questions/29149567/stop-javascript-function-execution-from-another-function) – Heretic Monkey Dec 26 '19 at 19:17
  • 2
    It might be helpful to provide some context; why do you think you need this? – jonrsharpe Dec 26 '19 at 19:18
  • What i was expecting (even if it's not the proper way) was something that really STOP the process. for exemple: ```Windows.internalprocess(process1.adress).Stop``` – Bojack Dec 26 '19 at 19:25

7 Answers7

2

You could try something like this:

var flag = true;
async function process1(){ //this is a normal function running
   while(flag){
      await sleep(50); //we suppose we have the function sleep.
      console.log("the function process1 is running...");
   }
}

function STOPprocess1(){
  flag = false;
}

But you may have problems with the scope...

Peyu
  • 401
  • 6
  • 15
  • Well this fit for the exemple that i provided. What i really search is something that stop a function no matter what, even without modifing the content of the ```process1``` function. I search something like ```Windows.InternalProcess(process1.adress).Stop()``` – Bojack Dec 26 '19 at 19:30
0

Use a global variable to stop process 1

let isRunning = true;

async function process1(){ //this is a normal function running
   while(isRunning){
     await sleep(50); //we suppose we have the function sleep.
     console.log("the function process1 is running...");
   }
}

function STOPprocess1(){
  isRunning = false; 
}
MikNiller
  • 1,242
  • 11
  • 17
0

How about using generator functions for that? If you yield, defer the call to .next() to a microtask, thus making it possible to interrupt:

  function interruptable(gen) {
     return function(...args) {
        let timer, it = gen(...args);
        function next() {
           const { done } = it.next();
           if(!done) timer = setTimeout(next, 0);
        }
        next();
        return () => clearTimeout(timer);
     };
 }

 const task = interruptable(function* () {
   while(true) {
      console.log("running");
      yield;
    }
 });

 const stop = task();
 setTimeout(stop, 1000);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

I would suggest setInterval over the use of a while loop (while(true) is generally frowned upon). You can then use clearInterval to stop execution.

let intervalId;

async function process1(){ //this is a normal function running
  intervalId = setInterval(() => console.log("the function process1 is running..."), 50);
}

function STOPprocess1(){
  clearInterval(intervalId)
}
aw04
  • 10,857
  • 10
  • 56
  • 89
0

while(true) might break your browser or whatever you're using. You can use setInterval() instead and use clearInterval() to stop the process.

    //before starting the function
    var process1;

    //when starting the function
    var process1 = setInterval(function() {
         console.log("the function process1 is running...");
    }, 50);

    //to stop the function
    function STOPprocess1(){
        clearInterval("process1");
    }
Yousername
  • 1,012
  • 5
  • 15
0

var cnt = 1;
var running = true;
process1();

async function process1(){ 
   if(running){
     await new Promise(resolve => setTimeout(resolve, 50));
     document.getElementById("tstArea").innerHTML="this: "+ cnt;
     cnt++;
     process1();
   }
}

function stopOtherFn(){
  running = false;
}
<div id="tstArea">
</div>
<button onClick="stopOtherFn()">StopThat</button>

here is a rough mockup that seems to accomplish what you are looking for.

NappingRabbit
  • 1,888
  • 1
  • 13
  • 18
0

If you want to iterate something without stopping instead another function asks for it:

I would not do that. I believe every function should control itself. If the function dedicated to stop another function append to fail, the cost in term of ressources and time to fix it may become problematic.

Instead, I'd create a function calling another function after checking something else (cookie, data, variable).

const checkSomething = () => {
    // var in parameter, cookie, data from API, etc
    // if necessary throw new Error
    if (something) return true;
    return false;
};

const something = () => {
    console.log('I did that');
};

const periodicallyDoSomething = () => {
    try {
        let continueDoingSomething = checkSomething();
        while (continueDoingSomething) {
            something();
            continueDoingSomething = checkSomething();
        }
    } catch (e) {
        console.error(e.message);
    } finally {
        console.log('I did it!');
    }
};

// run it, or export it as in module.exports

If you want a function to do something that takes a lot if time while still being able to stop it externally, like a classic CTRL+C:

This should be inside your function. I believe that a function dedicated to do something should be the same function finishing it.

Try/catch/finally, like I used it juste before, may be interesting.

Have a happy coding time. :)