<span style= "FONT-SIZE:18PX;" > Example:1</span>
function test () { var a = 1; SetTimeout (function () { alert (a); A = 5; }, 1000);} Test (); alert (0);//The two settimeout in front of it is delayed so perform this first
Result: Pop 0 first, then pop up 1.
Example 2
function test () { var a = 1; SetTimeout (function () { alert (a); A = 5; }, +); alert (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; }, +); A = 19;} Test (); alert (0);//The preceding alert is executed first because the settimeout is delayed.
Result: 0 will pop up first, then pop up.
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; }, +); A = 19;settimeout (function () { alert (a); A = 4; }, 3000);} Test (); alert (0);//The two settimeout in front of it is delayed so perform this first
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