In javascript how do asynchronous callbacks work i

2020-06-21 06:40发布

For the onload 2 functions below which are scheduled to be called 'onload' of these 2 images, what guarantees that one will completely finish before the other begins? Is there a queue behind the scenes of callbacks that need to fire in this single threaded environment?

if entryFunction never stops looping, does it pause its thread and yield to one of the doWorks()?

I've heard that javascript is not multithreaded, so is the entryFunction() yielding/pausing to these asynchronous function calls?

function entryFunction() {
  var obj = new Image();
  var obj2 = new Image();
  // ...
  obj.onload = function() { dowork(); }
  obj2.onload = function() { dowork(); }

  while (1) {
    console.log("Actual work is being done");
  }
}

function dowork() {
  doThis();
  doThat();
}

标签: javascript
4条回答
Root(大扎)
2楼-- · 2020-06-21 06:42

Both correct answers above me (that raw JS is single threaded and will block on that while). That said, there is a new HTML5 API called Web Workers that will give you concurrency in JS.

http://www.html5rocks.com/en/tutorials/workers/basics/

They are 'true' (in so far as the developer is concerned) concurrency. Some browsers do implement them as true concurrency, some fudge it with behind the scenes coroutines and schedulers.

查看更多
Explosion°爆炸
3楼-- · 2020-06-21 06:42

Javascript is not multithreaded but it is event-driven.

dowork() will be called unless onload() is called by something.

Apart from that while(1) will not cause the code to go forward. Instead of while(1) use setInterval or setTimeout. That way function doesn't block rest of the code.

Race condition is possible if new Image() cause onload() to be called as onload is being set after new Image()

查看更多
家丑人穷心不美
4楼-- · 2020-06-21 06:59

Nothing guarantees it.

You're only guaranteed they won't run at the same time.

The while loop will block other js from running.

The browser itself isn't limited to a single thread implementation. Javascript itself runs in a single run loop, but that doesn't guarantee the remainder of the things in the browser do (and they don't).

查看更多
5楼-- · 2020-06-21 07:08

Your code will not ever leave the while loop. Because JavaScript only has one thread, you must return from every function to return control back to the environment.

In your example, your example will cause your browser to set up and download images in separate threads (since the browser is multithreaded). When the images are downloaded, the environment will queue up calls to onload(). These would run the next time your JavaScript program returns control back to the environment.

But since you are holding control indefinitely in your while loop, control never returns to the environment, and the queued-up events will never run.

查看更多
登录 后发表回答