0

Here is a simple script:

    var _URL = window.URL || window.webkitURL;
    var img; 
    var img_width = 0; 
    var img_height = 0;
    var f = $(this)[0].files[0];  
    if (f != null) {
      if (f.type == 'image/jpeg') {
        img = new Image();
        img.onload = function () {
          img_width = this.width;  //why not $(this)??
          img_height = this.height;
          alert(img_width + ' x ' + img_height);  //1st alert
        };
        img.src = _URL.createObjectURL(f);
        alert(img_width + ' x ' + img_height); //2nd alert
      };
    };

The img_width & img_height are a global var and its value is reset with img.onload. When the script is executed, the first alert displays the width and height. However the 2nd alert always displays 0 x 0. Why the gloabl var img_width and img_height were not reset within img.onload for late use in main thread?

user938363
  • 9,990
  • 38
  • 137
  • 303
  • It won't work because the `onload` will be fired asynchronously – Arun P Johny Nov 23 '15 at 03:39
  • @user938363 The duplicate answer link is spot on. `onload` is an asynchronous call which does not execute inline. It executes after the image has completed it's load. Since the second `alert` is inline with the "main thread", after the onload function is set and is waiting to be triggered, the code continues on, calling the second alert before the image finishes. When the load fires off, the onload function is executed, and the first alert is called. – jwatts1980 Nov 23 '15 at 03:43
  • How to reset the value of img_width and img_height for late use in main thread? – user938363 Nov 23 '15 at 03:52

0 Answers0