停止从JavaScript中的ANOTHER函数运行的函数

时间:2019-12-26 19:11:37

标签: javascript function external

我想要做的是停止从ANOTHER函数(在JavaScript中)运行的函数。这是我想做的一个例子:

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

当我调用STOPprocess1()时,我希望process1函数停止运行。

7 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情:

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

但是您的范围可能有问题...

答案 1 :(得分:0)

使用全局变量停止进程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; 
}

答案 2 :(得分:0)

如何使用生成器函数呢?如果您yield,则将对.next()的调用推迟到微任务,从而可以中断:

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

答案 3 :(得分:0)

在使用setInterval循环的情况下,我建议使用while(通常不赞成while(true))。然后,您可以使用clearInterval停止执行。

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

答案 4 :(得分:0)

while(true)可能会破坏您的浏览器或您使用的任何设备。您可以改为使用setInterval(),然后使用clearInterval()停止该过程。

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

答案 5 :(得分: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>

这是一个粗略的模型,似乎可以满足您的需求。

答案 6 :(得分:0)

如果要迭代而不停止,则另一个函数会要求它:

我不会那样做。我相信每个功能都应该控制自己。如果专用于停止另一个功能的功能追加失败,那么在资源和修复该功能方面的成本可能会成问题。

相反,我会在检查其他内容(cookie,数据,变量)后创建一个调用另一个函数的函数

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

如果您希望某个函数执行一些需要花很多时间才能在外部停止的函数,例如经典的CTRL + C:

这应该在您的函数内部。 我认为,专门用于执行某项操作的功能应该与完成它的功能相同。

尝试/抓住/最后,就像我之前使用它一样,可能很有趣。

祝您编码愉快。 :)