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.

6
  • 3
    while(true) might break your browser or whatever you're using. You can use setInterval() instead and use clearInterval() to stop the process. Commented Dec 26, 2019 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. Commented Dec 26, 2019 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. Commented Dec 26, 2019 at 19:16
  • Does this answer your question? Stop Javascript Function execution from another Function Commented Dec 26, 2019 at 19:17
  • 2
    It might be helpful to provide some context; why do you think you need this? Commented Dec 26, 2019 at 19:18

7 Answers 7

3

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...

Sign up to request clarification or add additional context in comments.

1 Comment

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()
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; 
}

Comments

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);

Comments

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)
}

Comments

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");
    }

Comments

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.

Comments

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. :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.