1

What console log can be after this code will be executed?

var img = new Image;
img.onload = function() { console.log('B'); };
img.src = 'image.jpg';
for (var i=0;i<100000;i++) {
  console.log('A');
}

I know, that most likely it will be A...AB. But can it be A...B...A or BA...A? For example, if image.jpg is very small file and connection is very fast.

1

1 Answer 1

0

It can be any of them. You don't know how long it takes to load the image. The image could even be cached, minimizing the loading time.

Sign up to request clarification or add additional context in comments.

7 Comments

It's also worth noting that using the load event is notoriously unreliable. See the "caveats" section in api.jquery.com/load-event
But since javascript is single-threaded, that while we inside the loop any other code can not be executed, so the onload event can not be invoked because the thread is busy. Is it right?
@Andrey actually, it looks like you're right! All my tests in JSFiddle and this answer seem to point that the main() function has to finish executing before any asynchronous events can be triggered. Interesting - I always thought events were executed in another thread.
The BA...A is still unclear. I have not managed to get it in browser, but also can not find a proof that it can not be...
@Andrey M.: to get the AAABA the for loop should also be runned asynchronously, so maybe with a function launched by a SetTimeout and where the next loop iteration would also be called inside this function with a SetTimeout (recursive SetTimeout chain isntead of for loop). Then all pieces of coude would be taken from the asynchronous stack. In the current way it's written the load event will maybe terminate while you're in the for loop but the console.log('B') will wait until the end.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.