asynchronous - Is JavaScript callbacks blocking? - Stack Overflow

If I registered a time-consuming callback function to an event listener, and this event is fired twice

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745610483a4635918.html

相关推荐

  • asynchronous - Is JavaScript callbacks blocking? - Stack Overflow

    If I registered a time-consuming callback function to an event listener, and this event is fired twice

    10小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信