Javascript 创建新的“线程”

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

Javascript Create New "Thread"

javascriptasynchronous

提问by skeggse

This is a "thread" according to javascript, but the code doesn't seem to fit the conventional threaded model.

根据javascript,这是一个“线程”,但代码似乎不适合传统的线程模型。

Is it possible to make this code clearer, with regards to the concept of a thread?

关于线程的概念,是否可以使此代码更清晰?

function test() {
    alert("Test");
}

// this creates a new "thread," but doesn't make much sense to the untrained eye
setTimeout(test, 0); 

Is there some other way to branch off?

有没有其他方法可以分支?

回答by Felix Kling

You are basically just taking the call to testout of the normal flow and the engine will execute the function whenever it fits, as soon as possible. That means, you are executing testasynchronously.

您基本上只是将调用test从正常流程中取出,引擎将在合适的时候尽快执行该函数。这意味着,您正在test异步执行。

To make the code clearer, you could create a function with a meaningful name which does the same:

为了使代码更清晰,您可以创建一个具有有意义名称的函数,它的作用相同:

function executeAsync(func) {
    setTimeout(func, 0);
}

executeAsync(function() {
    alert("Test");
});

If you want to have real threads, have a look at web workers.

如果您想拥有真正的线程,请查看web workers