了解JavaScript的单线程性质 [英] Understanding JavaScript's single-threaded nature

查看:197
本文介绍了了解JavaScript的单线程性质的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读John Resig的JavaScript Ninja的秘密,它解释了JavaScript是单线程的。但是,我尝试测试这个,我不知道从这里带走:

I've been reading John Resig's "Secrets of a JavaScript Ninja" and it explains that JavaScript is single-threaded. However, I tried testing this and I'm not sure what to take away from here:

// executing this in browser
(function () {
    // throw something into event queue
    setTimeout(function () {
        alert("This will be called back after 1 second.");
    }, 1000);

    // arbitrary loop to take up some time
    for (var i = 0; i < 10000; i += 1) {
        console.log(i);
    }
})();

也许我不明白什么是单线程的意思,但我认为setTimeout回调将不会执行,直到所有外部匿名函数完成。然而,在浏览器中运行这显示回调函数被调用,而我仍然输出到控制台。对我来说,这似乎有2个线程与匿名函数的调用占用1个线程,然后回调使用第二个线程。

Maybe I'm not understanding exactly what being single-threaded means, but I thought that the setTimeout callback wouldn't execute until all of the outer anonymous function is complete. However, running this in the browser shows that the callback function gets called while i's are still being outputted onto the console. To me, this seems like there's 2 threads with anonymous function's invokation occupying 1 thread and then the callback using the 2nd thread.

有人可以帮助解散我吗? p>

Can someone help un-confuse me?

推荐答案

console.log()在某些浏览器中是一个奇怪的函数Chrome),并不是同步本身,所以你不能真正使用它来衡量单线程。你可能看到的是JS引擎执行所有的 console.log()语句,然后 setTimeout()运行以显示警报,并且(在非JavaScript的一些其他进程中)所有数据正在控制台中显示。

console.log() is a weird function in some browsers (like Chrome) and is not synchronous itself so you can't really use it to gauge the single threadedness. What you are probably seeing is that the JS engine executes all the console.log() statements and then the setTimeout() runs to show the alert and, in parallel (in some other process that isn't javascript) all the data is being shown in the console.

Javascript确实是单个螺纹。在您的示例中, setTimeout()回调将不会执行,直到循环完成。

Javascript is indeed single threaded. In your example, the setTimeout() callback will not execute until your for loop is done.

您可以更好地说明它:

(function () {
    // throw something into event queue
    setTimeout(function () {
        alert("This will be called back after 1 second.");
    }, 1000);

    function now() {
        return new Date().getTime();
    }
    var start = now();
    // loop for 1.2 seconds
    while (now() - start < 1200) {}
    alert("Looping done");
})();

工作jsFiddle演示: http://jsfiddle.net/jfriend00/3sBTb/

Working jsFiddle demo: http://jsfiddle.net/jfriend00/3sBTb/

这篇关于了解JavaScript的单线程性质的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆