The closure and timer of JS are implemented in this way.
This article mainly explains the "JS closures and timers to achieve", the article explains the content is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "JS closures and timers so realized" it!
What is a closure? What's the use?
A closure is a function that can read internal variables of other functions.
Function: 1. You can read the variable 2 inside the function. Keep the values of these variables in memory all the time.
What is the function of setTimeout0?
Js runs on a single-threaded basis, meaning that when a piece of code executes, other code goes into the queue and waits, and executes subsequent code once the thread is idle. If a setTimeout is set in the code, the browser will insert the code into the task queue at the appropriate time. If this time is set to 0, it will be inserted into the queue immediately, but not immediately, waiting for the previous code to finish execution (there is actually a delay, whether 16ms or 4ms depends on the browser). So setTimeout does not guarantee the time of execution, and whether it is executed in time depends on whether the JavaScript thread is crowded or idle.
Code
How much is the output of the following code? Modify the code to let fnArr [I] () output I. Use more than two methods
VarfnArr= []
For (vari=0;i