javascript 如何杀死一个javascript函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16947360/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:34:20  来源:igfitidea点击:

How to kill a javascript function?

javascriptasynchronouskill

提问by Goje87

sample code:

示例代码:

var isExecutionOver = false,
    myFunction = function() {
      // does some asynchronous stuff and sets isExecutionOver to true
      // when the asynchronous job is over.
    };

myFunction();

// Kill myFunction if it takes more than 3 seconds
setTimeout(function() {
  if(!isExecutionOver) {
    // How do I kill myFunction?
  }
}, 3*1000);

In the above snippet I am trying to kill (or in other words, stop execution of) myFunctionif it is not able to do its job in given time (3 seconds in this case).

在上面的代码片段中,myFunction如果它无法在给定的时间(在这种情况下为 3 秒)内完成其工作,我将尝试杀死(或换句话说,停止执行)。

PS: Kindly assume that I do not have control over myFunction definition. The only place where I can work is inside setTimeout.

PS:请假设我无法控制 myFunction 定义。我唯一可以工作的地方是里面setTimeout

回答by Lee Meador

You have a very complicated question:

你有一个非常复杂的问题:

  • You can't actually kill a running function. You can sometimes set a flag that it can notice when it decides to check. It could stop doing what it is doing and return.

    But remember that JavaScript is a single-threaded language. When the code in this function is running, there are few ways for any other code to set that flag.

    Example 1: It seems like I remember something about how some browsers, for example, will let certain events be run from the event queue when an alert box pops up. Those events could set the flag.

    Example 2: Another possibility is that the code in the function is not technically in the function but the function starts an interval timer that does the work. Any other code could set the flag and the code run at intervals could check the flag and stop repeating.

    var abortWork = false;
    function a() {
        while (notDone) {
            .. do some work ...
            if (abortWork) {
                return;
            }
        }
    }
    ... whatever ...
    abortWork = true;
    
  • You can stop a setTimeout()event that is waiting for the time to be over. (There is a similar way to stop a setInterval()repeated event.

    var t = setTimeout(function() {
            ... code goes here ...
        }, 20000);
    ... whatever ...
    clearTimeout(t); // stop the timeout if it hasn't started running the function
    
  • You can stop an ajax request that is waiting for the response. (Note: An XHR object is also returned from pure javascript ajax call.) Note that the request has already gone to the server and this just tells it to ignore any future response to the request.

    var xhr = $.ajax({ type: "POST", ... });
    ... whatever ...
    xhr.abort(); //kill the request
    
  • 你实际上不能杀死一个正在运行的函数。有时您可以设置一个标志,当它决定检查时可以注意到。它可以停止做它正在做的事情并返回。

    但请记住,JavaScript 是一种单线程语言。当此函数中的代码运行时,其他代码几乎没有办法设置该标志。

    示例 1:我好像记得一些浏览器是如何在弹出警告框时让某些浏览器从事件队列中运行某些事件的。这些事件可以设置标志。

    示例 2:另一种可能性是函数中的代码在技术上不在函数中,但函数会启动一个间隔计时器来完成工作。任何其他代码都可以设置标志,并且每隔一段时间运行的代码可以检查标志并停止重复。

    var abortWork = false;
    function a() {
        while (notDone) {
            .. do some work ...
            if (abortWork) {
                return;
            }
        }
    }
    ... whatever ...
    abortWork = true;
    
  • 您可以停止setTimeout()等待时间结束的事件。(有一种类似的方法可以停止setInterval()重复的事件。

    var t = setTimeout(function() {
            ... code goes here ...
        }, 20000);
    ... whatever ...
    clearTimeout(t); // stop the timeout if it hasn't started running the function
    
  • 您可以停止等待响应的 ajax 请求。(注意:纯 javascript ajax 调用也会返回一个 XHR 对象。)请注意,请求已经发送到服务器,这只是告诉它忽略对请求的任何未来响应。

    var xhr = $.ajax({ type: "POST", ... });
    ... whatever ...
    xhr.abort(); //kill the request