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.

Andrey M.
  • 3,688
  • 3
  • 33
  • 36
  • https://stackoverflow.com/questions/14648598/is-it-necessary-to-set-onload-function-before-setting-src-for-an-image-object/50783497#50783497 – xianshenglu Jun 10 '18 at 12:16

1 Answers1

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.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • It's also worth noting that using the `load` event is notoriously unreliable. See the "caveats" section in http://api.jquery.com/load-event/ – Pekka Sep 26 '11 at 08:49
  • 1
    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 M. Sep 26 '11 at 08:59
  • @Andrey actually, it looks like you're right! All my tests in JSFiddle and [this answer](http://stackoverflow.com/questions/3939315/are-callbacks-always-asynchronous/3939351#3939351) 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. – Pekka Sep 26 '11 at 09:06
  • 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. Sep 26 '11 at 09:13
  • @Andrey not if I understand the other answer right. According to that, `main()` has to finish executing before any events are triggered... But it would be interesting to get some more responses on this. – Pekka Sep 26 '11 at 09:15
  • 2
    @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. – regilero Sep 29 '11 at 07:59
  • Try it in IE7. In my experience the onload handler MUST be specified before the .src is set. – mplungjan Feb 01 '13 at 15:31