JavaScript回调是否会被阻止? [英] Is JavaScript callbacks blocking?

查看:63
本文介绍了JavaScript回调是否会被阻止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我向事件监听器注册了一个耗时的回调函数,那么这个事件会在短时间内触发两次。第二个回调是否会被第一个回调阻止?

If I registered a time-consuming callback function to an event listener, and this event is fired twice in a short period. Will the second callback be blocked by the first one?

我在浏览器中试过这个:

I tried this in browser:

document.body.onclick = function() {
    var date = new Date;
    console.log('click event at ' + date);

    while(new Date - date < 1e4) {};

    console.log('callback end');
}

结果,第二个回调在第一个完成后立即执行。

As the result, the second callback was executed right after the first one is done.

所以现在我对JavaScript非阻塞异步模块感到困惑:哪个部分是异步执行的?

So now I am confusing with the JavaScript non-blocking async module: which part has been executed asynchronously?

推荐答案

浏览器中的Javascript是单线程的,可以处理事件队列。在触发下一个事件之前,一个事件将运行完成。因此,如果在第一次处理仍然处理时发生第二次点击,则第二次点击将排队,并且在处理完第一次的代码完成之前不会运行。

Javascript in a browser is single threaded and works off an event queue. One event will run to completion before the next event is triggered. So, if a second click occurs while the first is still processing, the second click will be queued and will not run until the code processing the first one is done.

你可以在这里阅读有关此事件队列概念的更多信息:

You can read more about this event queue concept here:

JavaScript如何在后台处理AJAX响应?

在您的特定示例中,一旦您的代码开始运行,它就是全部同步的。 循环运行直到完成并且阻塞(保持任何其他Javascript运行直到完成)。

In your particular example, once your code starts running, it is all synchronous. The while loop runs until completion and is blocking (keeping any other Javascript from running until it is done).

有一些异步方法可以安排将来运行的某些代码(使用 setTimeout() setInterval())允许其他代码在此期间运行,但你没有使用那种机制。

There are asynchronous ways to schedule some code to run in the future (using setTimeout() or setInterval()) that would allow other code to run in the meantime, but you aren't using that mechanism.

这篇关于JavaScript回调是否会被阻止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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