在javascript中,异步回调如何在单个线程中工作? [英] In javascript how do asynchronous callbacks work in a single thread?

查看:57
本文介绍了在javascript中,异步回调如何在单个线程中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于下面的onload 2函数,它们被安排在这两个图像中被称为onload,是什么能保证一个在另一个图像开始之前完全完成?在这个单线程环境中是否需要触发回调的幕后队列?

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?

如果entryFunction从不停止循环,它是否会暂停其线程并屈服于其中一个doWorks()?

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

我听说javascript不是多线程的,所以entryFunction()是否会产生/暂停这些异步函数调用?

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只有一个线程,所以每个函数必须返回才能将控制权返还给环境。

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例如,您的示例将使您的浏览器在单独的线程中设置和下载图像(因为浏览器是多线程的)。下载图像后,环境会将调用排队到 onload()。这些将在您的JavaScript程序下次将控制权返回到环境时运行。

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.

这篇关于在javascript中,异步回调如何在单个线程中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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