|
function test() {
var a =
1
;
setTimeout(function() {
alert(a);
a =
5
;
},
1000
);
}
test();
alert(
0
);
//前面的两个setTimeout延迟了 所以先执行这个
|
Result: Pop 0 first, then pop up 1.
Example 2
|
function test() {
var a =
1
;
setTimeout(function() {
alert(a);
a =
5
;
},
1000
);
lert(a);
}
test();
alert(
0
);
|
Result: pops up 1 First, then pops 0, and finally pops up 1.
The alert () in test () is executed first because the function is not executed at this time, so a is still 1. Because the function is delayed, the alert (0) is executed, and the last time, the alert (a) is executed, because the previous a has become 1, so , and the last popup is 1.
Example: 3:
|
function test() {
var a =
1
;
setTimeout(function() {
alert(a);
a =
5
;
},
1000
);
a =
19
;
}
test();
alert(
0
);
//前面的alert因为setTimeout延迟了 所以先执行这个。
|
Result: The 0 will pop up first and then pop up 19.
Deferred function () {
alert (a);
A = 5;
}
But the a=19 will still execute, not wait until the end of the delay. So, when executing this delayed function, a=19!
Example 4
|
function test() {
var a =
1
;
setTimeout(function() {
alert(a);
a =
5
;
},
1000
);
a =
19
;
setTimeout(function() {
alert(a);
a =
4
;
},
3000
);
}
test();
alert(
0
);
//前面的两个setTimeout延迟了 所以先执行这个
|
Result: Will pop up 0 first, then pop up 19, and finally pop up 5.
Additional explanations for global variables and local variables!
Global variables: Defined outside a function, or assigned within a function but not preceded by the VAR keyword, are global variables
Local variables: variables defined within a function and preceded by a var keyword
A few examples to figure out how JS's settimeout works