JavaScriptsetTimeout uses the closure function to implement timed printing of numerical value _ javascript skills

Source: Internet
Author: User
This article mainly introduces the use of the closure function of JavaScriptsetTimeout to implement timed printing of numerical data. For more information, see setTimeout. in fact, in the early days, it was also a mistake I often made. Or to implement this kind of capability, it seems that js is far-fetched. It is actually my fault. Haha! Failed to understand the power of JS. Let's go to the topic! NOTE: If setInterval is used for implementation, it must be very simple. This time we use setTimeout. Let's start with the simplest thinking. Then we will write the following code.

for(var i = 0; i < 5; i++){ setTimeout(console.log(i),i*1000); } 

Although this code is printed in sequence, each I value is 0, 1, 2, 3, 4. However, the execution time does not work. Why? Because console. log () is the method execution call, after calling this method, it should be executed immediately !, So we did not achieve our intended purpose.

Let's continue to look at the following code.

for(var i = 0; i< 5; i++ ){ setTimeout(function(){ console.log(i); },i*1000); } 

Here we use an anonymous function that contains the printed console. log to print the I, so the I value is shared. Before the first setTimeout is executed, the for loop has been executed, and the last I = 5, so I will print four times. In fact, we have two solutions. Let's first look at the first one:

var j = 0; function abc(){ console.log("j = "+j); j++; }  for(var i = 0; i < 10; i++ ){ setTimeout(abc,i*1000) } 

Here, we use another global variable to store the value. Every time the Values Function abc and j are executed, the abc function is called when setTimeout is executed, therefore, it will achieve our expected results, but here j is a global variable, which may easily change its value or name conflict. the implementation of the second method introduces the closure function again. because of the closure function, each creation has its own space to store unique values. so use this thinking. we will write the code below.

for(var i = 0; i < 10; i++ ){ (function(x){ setTimeout(function(){ console.log(x) },x*1000) })(i) }  

We pass the value of every execution of the for Loop of I to different created closure functions, so that the I value stored in each closure function will not be the same. so it is to achieve what we want.

Ps: simple encapsulation of setTimeout using closures

Some Spelling functions are often used when writing js scripts, such as calling setTimeout.

var msgalert="test";  function TestAlert(msg)    {     alert(msg)    }        $(document).ready(function () {   $("#btnCancel").click(function (e) {     setTimeout("TestAlert("+msgalert+")",1000);     }); }) 

After checking for a long time, why can't the dialog box be displayed. After checking for a long time, we found that a pair of single quotes were missing.

$(document).ready(function () {   $("#btnCancel").click(function (e) {     setTimeout("TestAlert('"+msgalert+"')",1000);     }); }) 

This writing method is prone to errors, and it is not easy to check for errors. If you use closures, you can avoid them completely. Rewrite the following:

 var msgalert="test";   function dalayAlert(msg ,time){    setTimeout(   TestAlert(msg),   time   );   }   function TestAlert(msg)  {   alert(msg)  } $(document).ready(function () {   $("#btnCancel").click(function (e) {    dalayAlert(msgalert,1000)  }); 

Since closures are used, they are much simpler and it is easy to check errors.

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: 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.