A few examples to figure out how JS's settimeout works

Source: Internet
Author: User

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

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.