停止从另一个函数执行Javascript函数

Stop Javascript Function execution from another Function

本文关键字:函数 执行 Javascript 另一个      更新时间:2023-09-26

有什么方法可以停止从另一个函数执行被调用的函数吗?

我有以下代码:-

function MainFunction() { //a long code that runs for few time  };
MainFuntion();
<button onclick="(Here I want some thing to stop MainFunction())">Stop the running script </button>

所以基本思想是从另一个函数

返回一个函数

JavaScript通常是单线程的,这意味着在浏览器中执行函数时,没有其他代码可以同时运行,包括onclick等事件处理程序(只有在函数完成后才会触发它们)。因此,在这种情况下,您不能从代码中断函数的执行。

有两种工作环境:

  1. 长时间运行的函数可能会故意中断,从而允许其他代码执行。

    //set this to true from an event handler to stop the execution
    var cancelled = false;
    function longRunningFunction() {
      if (cancelled) {
        return;
      } 
      // do some work, but not all
      // save your progress to be able to resume when called again
      if (!done) {
        // release control, so that handlers can be called, and continue in 10ms
        setTimeout(longRunningFunction, 10);
      }
    }
    
  2. 使用网络工作者。它们允许并行运行代码,但有一些限制,并非所有浏览器都支持。

无论何时调用MainFunction,都可以传递一个参数,如cancel。因此,如果你想让函数启动,你可以传递一个自变量"0",如果你希望它停止,你可以用一个不是"0"的自变量再次调用函数,比如"1"。下面是一个工作示例:

function MainFunction(cancel) {
var yourcode;
  if (cancel == 0) {
    yourCode = setInterval(function() {
      //Put your code here, this is an example:
      document.getElementById('div').style.color = "red";
    }, 1);
  }
  if (cancel == 1) {
    clearInterval(yourCode);
    document.getElementById('div').style.color = "black";
  }
}
<html>
  <head>
    <title>My website</title>
  </head>
  <body>
    <button id="btn" onclick="MainFunction(0)">Start</button>
    <button onclick="MainFunction(1)">Stop</button>
    <div id="div">This division can change colour</div>
  </body>
</html>

我认为您正试图停止执行函数中的其他函数调用。如果是,则需要将调用的函数放入条件中,以便控制执行。

如果我的理解不正确,请详细说明你想做什么,为什么要停止执行函数。

您可以使用setTimeoutclearTimeout

something.onclick('timeout()')
something.onclik('myStopFunction()')
var myVar;
function timeout() {
  myVar = setTimeout(()=>{MainFuntion(); }, 3000);
}
function myStopFunction() {
  clearTimeout(myVar);
}

有关详细信息,请查看此链接https://www.w3schools.com/jsref/met_win_cleartimeout.asp