Home  >  Article  >  Web Front-end  >  JavaScript setTimeout uses closure function to print values ​​regularly_javascript skills

JavaScript setTimeout uses closure function to print values ​​regularly_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:24:481331browse

This time we use setTimeout to implement an example of printing values ​​​​sequentially according to time. In fact, in the early days, it was also a mistake I often made, or to achieve this ability, it seems that js is far-fetched, but it is actually my Wrong, haha! I didn’t understand the power of JS. Let’s go directly to the topic! Note that if you use setInterval to implement it, it must be very simple. This time we use setTimeout. Let’s start with the simplest thinking. Then it will Write the following code.

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

Although this code prints the value of each i in sequence, 0, 1, 2, 3, 4. However, the execution time does not play a role. Why? Because console.log() is the execution call of the method , after calling this method, it is executed immediately!, so it does not achieve our expected purpose.

Then let’s continue looking at the following piece of 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 i, so the value of i is shared. Before the first setTimeout is executed, the for loop has been executed, and the final i = 5 , so i will be printed four times. In fact, we have two solutions. Let’s look at the first one first:

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

Here we have another global variable to store the value. Every time the function abc is executed, j is added once, so when setTimeout is executed, the abc function will be called, so the expected effect will be achieved, but here j is A global variable, global variables will cause problems such as easy to change its value or naming conflicts. To implement the second method, we introduce the closure function again. Because of the closure function, every time it is created, there will be its own space to store the unique value. So using this thinking. We write the code as follows.

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

We pass the value of i each time the for loop is executed to different created closure functions, so that the value of i stored in each closure function will be different. So we achieve what we want Result.

ps: Use closure to simply encapsulate setTimeout

When writing js scripts, some spelling functions are often used, such as calling setTimeout

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

I checked for a long time, why the dialog box doesn’t pop up. After checking for a long time, I discovered that a pair of single quotes

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

This way of writing is prone to errors, and it is not easy to detect errors. If you use closures, you can completely avoid it. Rewrite it as follows

 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) 
 }); 

Due to the use of closures, it is much simpler and error checking is also easy

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn