简体   繁体   English

同时执行2个功能。 可能吗?

[英]2 functions executed at the same time. Is it possible?

Let's assume I have the following code: 假设我有以下代码:

var funcIsRunning = 0;
function a(){
   funcIsRunning = 1;
   // some code ... (maybe lots of code);
   funcIsRunning = 0;
}

Is there any chance that some asynchronous function will catch funcIsRunning flag in '1' position? 某些异步函数是否有可能将funcIsRunning标志捕获到“ 1”位置? (eg the callback of XHR or a function that is called via setTimeout, etc.) Or, which is the same, can two functions be executed at the same time (not one after another)? (例如,XHR的回调或通过setTimeout调用的函数等),或者相同,是否可以同时执行两个函数(而不是一个接一个)?

Just to make it clear... In fact, I don't have to run 2 funcs simultaneously... I'm just wondering how it works. 为了清楚起见...实际上,我不必同时运行2个func ...我只是想知道它是如何工作的。

PS I would be very grateful if you could provide documentation/grounding of your answer Thanks a lot! 附言:如果您能提供文档/答案的基础,我将不胜感激。非常感谢


Made a test here that illustrates given answers: http://jsfiddle.net/rz7tvyof/ 在此处进行了测试,以说明给出的答案: http : //jsfiddle.net/rz7tvyof/

No, JavaScript is single threaded and runs only one function at a time. 不,JavaScript是单线程的,一次仅运行一个功能。 Although, if you have a callback function waiting for, say, a network request that happens to return at funcIsRunning = 1 , that callback function will be put on the queue that is handled by the event loop 虽然,如果您有一个回调函数正在等待某个网络请求,而该请求恰好在funcIsRunning = 1时返回,则该回调函数将被放入事件循环处理的队列中

JavaScript event loop explained JavaScript事件循环说明

Normally no thanks to event loop. 通常不感谢事件循环。 But you can use Web Workers to run code in parallel (with some limitations such as access to DOM etc.). 但是您可以使用Web Workers并行运行代码(有一些限制,例如对DOM的访问等)。

Worker documentation 工人文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM