Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript setTime() with Call back VS. with anonymous function

Tags:

javascript

I found the following two examples of setTime function, although the code looks the same, the result is different in the two cases.

Example1: Result "Hello Stack Overflow"

var a = "world";  
setTimeout(function(){alert("Hello " + a)}, 2000);  
a = "Stack Overflow";    

Example2: Result "Hello world"

function callback(a){  
    return function(){  
        alert("Hello " + a);  
    }  
}  
var a = "world";    
setTimeout(callback(a), 2000);    
a = "Stack Overflow";    

Why in the first example the value of a changed, and in excample2 it didn't?

like image 710
Ahmed Waheed Avatar asked Jun 07 '26 22:06

Ahmed Waheed


2 Answers

In the first example, the function reads the value of a directly. In the second example, the function reads the value of the parameter passed to it's factory function. Even though we reassign the value of the variable later, that doesn't affect the value of the parameter. It might be more clear if a different name is used for the parameter:

function callback(x){  
    return function(){  
        alert("Hello " + x);  
    }  
}  
var a = "world";    
setTimeout(callback(a), 2000);    
a = "Stack Overflow";

If you had used an object, you'd have a different story. Modifying your examples slightly, these both have the same result:

Example 1

var o = {};
o.a = "world";
setTimeout(function(){alert("Hello " + o.a)}, 2000);  
o.a = "Stack Overflow";

Example 2

function callback(obj){  
    return function(){  
        alert("Hello " + obj.a);  
    }  
} 
var o = {};
o.a = "world";
setTimeout(callback(o), 2000);    
o.a = "Stack Overflow";    
like image 181
gilly3 Avatar answered Jun 09 '26 10:06

gilly3


It doesn't change in the second example because you are actually creating a new local variable a as the argument to the callback function. So when you change the value of the global a it doesn't effect the value of the a inside that function.

  • global var a points at the string "world"
  • global var a gets passed to function
  • local var a is created and set to the value of global var a
  • global var a is set to a new value
  • function later runs, and uses the value of local var a

So because function arguments have the semantics of local variables, you can't change it after the fact like this.

like image 22
Alex Wayne Avatar answered Jun 09 '26 11:06

Alex Wayne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!