0

This code checks if exist a image or not.

Inside the function onload I would like to change the variable 'control' with a boolean value.

var control = 'a.jpg';
var image_name = control;
var image = new Image();

image.onload = function() {
    control = true; // Why this change does not happen outside of this function?
};
image.onerror = function() {
    control = false; // Why this change does not happen outside of this function?
};
image.src = image_name;

console.log(control); // The value is not changed in a boolean

But outside the function, the variable is not changed. Why?

Thanks

Mer
  • 93
  • 1
  • 1
  • 11

2 Answers2

0

That's because the console.log(control); is called before the onload or onerror functions of image are called.

The control variable changes but you call the log before it changes. You can modify your code to something like this in order to achieve what you want:

var control = 'a.jpg';
var image_name = control;
var image = new Image();

image.onload = function() {
    control = true;
    after();
};
image.onerror = function() {        
    control = false;
    after();
};
image.src = image_name;

function after(){
    alert(control);
    console.log(control);
}

You can also check it in this JSFiddle.

Thanasis1101
  • 1,614
  • 4
  • 17
  • 28
0

The function image.onload only execute after loading the images, it may take 500-1200ms execute,

console.log(control); executing before loading the image thats why alway shown as false

try to print the control value after few sec delay

var control = 'a.jpg';
var image_name = control;
var image = new Image();

image.onload = function() {
    control = true; // Why this change does not happen outside of this function?
};
image.onerror = function() {
    control = false; // Why this change does not happen outside of this function?
};
image.src = image_name;
setTimeout(function(){ 
console.log(control); // its work
},2000);

Change your code structure like this

var control = 'a.jpg';
var image_name = control;
var image = new Image();

image.onload = function() {
    control = true; 
    nextProcess();
};
image.onerror = function() {
    control = false; 
    nextProcess();
};
image.src = image_name;
function nextProcess(){
  console.log(control);
}
Sajan
  • 813
  • 9
  • 14