0

I want to pass a global parameter to a function in a setTimeout, but I want the value to stay at when the setTimeout is interpreted:

var a=0;

setTimeout(function(){
 console.log(a);
},5000,a)

a=1;

//output is 1 and should be 0

How can I fix this? I already searched Stack Overflow for an answer but didn't find anything.

Jeroen
  • 60,696
  • 40
  • 206
  • 339
lopata
  • 1,325
  • 1
  • 10
  • 23

4 Answers4

10

That's because you are still actually using the outer variable. Just add the parameter to the function:

setTimeout(function (a) {
    console.log(a);
}, 5000, a);
Razem
  • 1,421
  • 11
  • 14
0
  var a = 0;

    setTimeout(function(c) {
      console.log(c);
    }, 5000, a);

    a = 1;
Daniël Camps
  • 1,737
  • 1
  • 22
  • 33
0

You can use closure method to do the same than previous answers :

var a=0;
function func(b){
   var c = b;
   this.display = function(){
       console.log(c); 
   }
}

var functionDisplay = new func(a);

setTimeout(function(){
    functionDisplay.display();
},5000)

a=1;
OrcusZ
  • 3,555
  • 2
  • 31
  • 48
0

The problem here is that inside your setTimeout function the variable is getting referenced to the outer scope's variable reference. So you need to create a different scope for your setTimeout function as following:

        var a = 0;

        setTimeout((function(a) {
            return function() {
                console.log(a, arguments);
            }
        })(a), 5000)

        a = 1;
Raju Bera
  • 948
  • 8
  • 14