The settimeout of JavaScript learning

Source: Internet
Author: User

The fourth edition of the JavaScript authoritative guide says "Window object method settimeout () is used to schedule a JavaScript snippet to run at a specified time in the future."

SetTimeout (Foo,i); Foo is the callback function, I is the delay time

Note that the word "future", SetTime will put the Foo function in the queue, when the thread is idle, JavaScript will execute the event in the queue.

Look at the following code:

<!DOCTYPE HTML><HTML>  <Head>    <Scripttype= "Text/javascript">window.onload= function () {        vara= 0; functionOne () { for (varI= 0; I< Ten; I++) {console.log (i); SetTimeout (function() {console.log (a); A+=i; },0);      }; }      functionBoth () {alert (a);        } one (); SetTimeout (both,0); }    </Script>  </Head></HTML>

In fact, the one function looks like it will normally add a from 0 to 9, then alert out.

But the actual alert result is , why?

The For loop of the one function does not stop because it settimeout, and when it encounters settimeout, it simply puts the callback function inside the queue and continues to i++. Wait until all the for loops are executed to execute the function just put into the queue. Because the loop is over, I is 10, with a total of 10 identical a+=i, the function of the operation is called, and the result of a finally becomes 100.

But in fact the above code Part I still do not understand, is if settimeout (two,0), change to settimeout (0), then the result of alert becomes 0.

The first parameter of settimeout is the function object, and if it becomes two (), the callback function becomes the return value of two.

The settimeout of JavaScript learning

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.