最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

asynchronous - Is JavaScript callbacks blocking? - Stack Overflow

programmeradmin2浏览0评论

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.

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

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.

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

Share Improve this question asked Apr 18, 2015 at 6:29 Dolphin_WoodDolphin_Wood 8776 silver badges20 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

Javascript in a browser is single threaded and works off an event queue. One event will run to pletion 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:

How does JavaScript handle AJAX responses in the background?


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

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.

发布评论

评论列表(0)

  1. 暂无评论