Reputation: 34630
Was wondering if somebody could clarify the following:
// Gets fired 10000 times
fireEvent( function(){
console.log( 'first' );
setTimeout( ( function(){ console.log( 'second' ); } ), 100 );
});
This will output 10000 x "first" and then 10000 x "second". Is it because console.log( 'first' ) gets queued first in the event loop before the console.log( 'second' )?
Upvotes: 0
Views: 1411
Reputation: 9925
You are passing a function (literal) to the function fireEvent, that fireEvent presumably calls at some point... but you haven't pasted the code for fireEvent for us to know what fireEvent does exactly. Also, how is fireEvent() being called? Is it being called 1000 times in a loop?
For now, hopefully the following example might be helpful to understand what's going on.
function foo() {
console.log( 'first' );
setTimeout( ( function(){ console.log( 'second' ); } ), 100 );
}
for (var i = 0; i < 1000; i++) {
foo();
}
This will print 'first' a thousand times, and then 'second' a thousand times.
In this case, it should be fairly obvious what's going on: The for loop completes in less than the timeout period of 100 seconds, so each call it makes to foo() prints 'first' and returns before callbacks which print 'second' get a chance to execute.
However, and this is the interesting bit, even if the timeout period was very small (say 5 ms) and the loop ran a million times, you would still get 'first' printed a million times followed by 'second' getting printed a million times. (Even though the loop might now take longer than 5ms to execute).
function foo() {
console.log( 'first' );
setTimeout( ( function(){ console.log( 'second' ); } ), 5);
}
for (var i = 0; i < 1000000; i++) {
foo();
}
This happens because setTimeout only sets the minimum period after which the callback will be called. JavaScript is single threaded. If an event fires (or a callback's timeout period times out), its handler will be executed if nothing is going on, i.e. if the event loop is idle. However, if the timeout fires, and the javascript event loop is busy, the callback (and any subsequent events ready to be handled etc) will be put on a queue till the event loop is free to execute them.
Hope this helps.
Upvotes: 4