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

Source: Internet
Author: User

<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

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.