Reputation: 1866
function f(id) {
$.ajax("http://example.com/example",{
success:function(data, textStatus, jqXHR){
$("#"+id).text(data);
}
});
}
Success callback function can reach and read id
variable just fine, but since ajax calls are non-blocking, won't id
change with another function f()
call, happening after starting ajax request but before getting response? How can I save and pass the id
at the time of requesting ajax call?
Upvotes: 2
Views: 73
Reputation: 8491
won't id change with another function f() call
No, because every time a function is called, a copy of the variable passed as a parameter is created.
Consider the following situation:
let a = 1;
function change(param) {
param = 2;
console.log(param);
}
change(a);
console.log(a);
This code will print 2
and then 1
because param
is a copy of a
and therefore changing it doesn't affect a
.
Things become a little more complicated when passing a reference to an object:
let a = {field: 1};
function change(param) {
param.field = 2; // changes the original object field
param = {field: 7}; // changes the value of param variable
console.log(param.field);
}
change(a);
console.log(a.field);
The console will print 7
and then 2
. In this case a
is a reference, not a primitive value. And although param
is a copy of a
, it is a copy of the reference, and this copy refers to the same object.
So param.field = 2
changes the field
of the original object. That's why we get 2
in the second output.
But if we assign a new value to param
, we overwrite the reference to a
with a reference to the new object {field: 7}
. And since param
is a copy of a
, original object is not affected.
Upvotes: 2
Reputation: 2759
No, it won't change. It will start an entire new ajax
request with it own success callback. Which will, most likely, resolve sometime after the first one updating it again. This is true even if you called f()
again BEFORE the server returns a response to you. Your scope will be preserved.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
Upvotes: 1