javascript js - 检查一个函数是否完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22323938/
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 22:55:31  来源:igfitidea点击:

js - check if a function is completed

javascriptfunction

提问by Lewis

I want to set a hotkey to several functions by jquery hotkeys. And I need to check if a function is finished, may be something like:

我想通过 jquery 热键为几个功能设置一个热键。我需要检查一个函数是否完成,可能是这样的:

if("function A is completed")
{
    "Ctrl+A is now set to function B"
}
else
{
    "Ctrl+A is set to function A"
}

How could I check this? Or any better ideas?

我怎么能检查这个?或者有什么更好的想法?

采纳答案by T.J. Crowder

JavaScript on web browsers is single-threaded (barring the use of web workers, and even with those a function can't be interrupted), so except for a couple of bugs inissueswith Firefox, a function cannotbe interrupted in the middle. So if your code is running, the other function is not, by definition.

的JavaScript的Web浏览器是单线程(禁止使用网络工作者,甚至与那些功能不能中断),所以除了几个中的错误问题与Firefox,功能不能在中途中断。因此,如果您的代码正在运行,那么根据定义,另一个函数不会运行。

(For details on the issues with Firefox, see this answer by bobinceabout some very edge-case scenarios.)

(有关 Firefox 问题的详细信息,请参阅bobince关于一些非常边缘情况的答案。)

回答by Zanderi

Depending on the situation there are a couple of things you can do. You can call the function when you've finished completing the current function or you can set a boolean for the same thing.

根据具体情况,您可以做几件事。您可以在完成当前函数后调用该函数,也可以为同一事物设置一个布尔值。

function A(){
  alert('run items in function A');
  return fireNewFunctionWhenComplete()
}

or set a flag

或设置一个标志

/*global var*/
var functionBCompleted = false;

function B(){
  alert('run items in function B');
   return functionBCompleted = true;  
}

function testFunctionComplete(){
  if(functionBCompleted){
    alert('function B Copmleted');
  }
  else{
    alert('function B not run');
  }
}

This is a very simple example and as @T.J. mentioned you can't interrupt a running process. However, you may want to take a look into the promises spec if you want to run something when an asynchronous operation has completed.

这是一个非常简单的例子,正如@TJ 提到的,你不能中断正在运行的进程。但是,如果您想在异步操作完成后运行某些内容,您可能需要查看 promise 规范。