-2

The console log shows me "active" but the "blocks" variable is still false and shows me "not active" in the alert.

var blocks = false;

(function(){  
 var test = document.createElement('div');
 test.innerHTML = ' ';
 test.className = 'adsbox';
 document.body.appendChild(test);
 window.setTimeout(function() {

if (test.offsetHeight === 0) {

  var blocks = true;
  console.log("active");

} else {

var blocks = true;
console.log("not active");

}
test.remove();
}, 200);
})();

Here the check if the variable is true:

if (blocks) {

alert('active');

}else{

alert('not active');

}

Why is "block" always false and how can I use the "block" variable after the function?

labu77
  • 605
  • 1
  • 9
  • 30

4 Answers4

2

You have two different variables called block.

One inside the anonymous function you pass to setTimeout and one global.

Remove var from the inside function so you don't declare the new variable in the narrow scope (and mask access to the global).


Note that since your if (blocks) statement appears to just be after the rest of your code, making the above modification so the global variable gets modified won't make any practical difference. You would still be testing the value of it before the timeout occured.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

You are creating a new blocks inside of the function, not using the top level one. Drop the var from the var blocks = true lines inside of the function.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
0

Drop the keyword var from your assignment. You're creating a new variable in the local scope that happens to have the same name. The outer variable is not being assigned.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
0

It's because of the scope of your variables. You have what looks to be a global variable, blocks, and then you also have local variables blocks also defined in each branch. You need to set the value of the global blocks, not create new local blocks.

Jacob
  • 91
  • 1
  • 9