在设立监听器之前会触发事件吗?

var a = new Image(); ... // Is it possible that `load` happens here, so I won't be able to catch it? ... a.onload = function () {}; 

那么,我猜load事件将不会被触发。

浏览器如何神奇地确保通过循环运行代码? 那么事件只有在完成了本轮之后才会触发?

下面的代码将不会输出任何东西,是不是因为使用setTimeout我们让foo运行在另一轮

 var a = require('child_process').spawn('ls', ['-l']); setTimeout(function foo() { a.stdout.on('data', function (data) { console.log(data.toString()); }); }, 1000); 

浏览器如何神奇地确保通过循环运行代码? 那么事件只有在完成了本轮之后才会触发?

是。 或者至less它应该,我不认为这是在所有浏览器和所有边缘情况下(例如caching文件)100%的保证。 所以你应该在build立监听之后开始加载(通过分配src属性):

 var a = new Image(); // Is it possible that `load` happens here? No. a.onload = function () {}; a.src = ""; // Is it possible that `load` happens here? Yes 

下面的代码将不会输出任何东西,是不是因为使用setTimeout我们让foo运行在另一轮?

究竟。 当然,它可能(不太可能)发生,你的服务器很慢,并且ls -l在输出之前需要一秒以上的时间,那么你就会抓住它。

代码不会产生任何东西,因为如您所怀疑的,它在您设置侦听器之前完成。

 Time Event 00.000 Spawn Child process 12345 `ls` with arguments `-l` (a) 00.001 Set Timeout for function foo() in 1 second. 00.011 child process 12345 terminated with data. (a) 01.001 Running foo() 01.002 Attach 'data' event to `a` 

基本上,你错过了公交车(从字面上看,如果你把它看作一个串行总线)

你应该不使用setTimeout并且链接它,如果你想抓住它。

 var a = require('child_process').spawn('ls', ['-l']).stdout.on('data', function (data) { console.log(data.toString()); });