javascript可以一次运行多个函数吗

javascript可以一次运行多个函数吗

本文介绍了javascript可以一次运行多个函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以同时调用多个函数?

Is it possible to call multiple functions at the same time?

例如

var executed = false;
// loop 1
func();
// loop 2
func();

function func(){
    if (executed) return;
    executed = true;
    alert(1);
}

func() 可以一次执行 2 次吗?

Can func() be executed 2 times at once?

推荐答案

JavaScript 不支持同时运行多个函数.从历史上看,它依赖于使用向 JS 提供 API 的本机代码处理耗时的任务(例如等待 HTTP 请求或执行 CPU 密集型操作)(并且该 API 接受回调,或者最近返回一个承诺).

JavaScript has no native support for running multiple functions simultaneously. It has, historically, depended on time-consuming tasks (such as waiting for an HTTP request or doing something CPU intensive) being handled with native code that presents an API to JS (and that API accepting a callback or, more recently, returning a Promise).

情况开始改变.

大多数网络浏览器都支持 Web Workers 和Node.js 引入了对工作线程的实验性支持.

Most web browsers support Web Workers and Node.js has introduced experimental support for Worker Threads.

这些都允许将 JavaScript 代码分配到一个单独的进程,该进程独立于主事件循环运行,并使用消息与主进程通信.

These each allow JavaScript code to be farmed off to a separate process which runs independently of the main event loop and communicate with the main process using messages.

这篇关于javascript可以一次运行多个函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 06:47