Several examples illustrate how to run setTimeout in JS.

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.