Several examples illustrate how to run setTimeout in JS.
Example: 1
Function test () {var a = 1; setTimeout (function () {alert (a); a = 5 ;}, 1000) ;}test (); alert (0 ); // The first two settimeouts are delayed. Therefore, execute this
Result: 0 is displayed, and 1 is displayed.
Example 2
function test() { var a = 1; setTimeout(function() { alert(a); a = 5; }, 1000); alert(a);}test();alert(0);
Result: 1 is displayed, 0 is displayed, and 1 is displayed.
Execute alert () in test () first, because the function is not executed yet, so a is still 1. because the function is still delayed, alert (0) is executed, and the last time is reached, alert (a) is executed. Because a has changed to 1, the last pop-up is 1.
Example: 3:
Function test () {var a = 1; setTimeout (function () {alert (a); a = 5 ;}, 1000); a = 19 ;}test (); alert (0); // The preceding alert is executed first because of the delay of setTimeout.
Result: 0 is displayed, and 19 is displayed.
Function (){
Alert ();
A = 5;
}
But a = 19 will still be executed as usual, instead of waiting until the delay ends. Therefore, 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); // The first two settimeouts are delayed.
Result: 0 is displayed, 19 is displayed, and 5 is displayed.
Additional explanations: global variables and local variables!
Global variables: defined outside the function, or assigned values in the function, but the var keyword is not added before, are global variables.
Local variables: variables defined within the function with the preceding var keyword