JS closures and timers
This time I will bring you JS closures and timers. What are the precautions when using JS closures and timers? The following is a practical case, let’s take a look together. take a look.
What is a closure? What is its function
A closure is a function that can read the internal variables of other functions.
Function: 1. You can read the variables inside the function 2. Keep the values of these variables in memory.
What is the role of setTimeout 0
JS operation is based on a single thread, which means that when a piece of code is executed, other codes will enter the queue to wait, and subsequent codes will be executed once the thread is free. 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 means that it will be inserted into the queue immediately, but it will not be executed immediately. You will still have to wait for the previous code to execute. Completed (actually there is a delay, whether it is 16ms or 4ms depends on the browser). Therefore, setTimeout does not guarantee the execution time. Whether it is executed in time depends on whether JavaScript the thread is crowded or idle.
Code
How much does the following code output? Modify the code so that fnArr[i]() outputs i. Use more than two methods
var fnArr = []; for (var i = 0; i < 10; i ++) { fnArr[i] = function(){ return i; }; } console.log( fnArr3 ); //
Code:
Method one:
var fnArr = []; for (var i = 0; i < 10; i ++) { fnArr[i] = (function(){ var index = i; var fn = function(){ return index } return fn }()); } console.log( fnArr3 ); //
Method two:
var fnArr = []; for (var i = 0; i < 10; i ++) { (function(n){ fnArr[i] = function(){ return n; } })(i) }; console.log( fnArr3 )
Use closure Encapsulating a car object, you can obtain the car status in the following way
var Car = //todo; Car.setSpeed(30); Car.getSpeed(); //30 Car.accelerate(); Car.getSpeed(); //40; Car.decelerate(); Car.decelerate(); Car.getSpeed(); //20 Car.getStatus(); // 'running'; Car.decelerate(); Car.decelerate(); Car.getStatus(); //'stop'; //Car.speed; //error
Code:
var Car = (function(){ var speed; function setSpeed(n){ speed = n } function getSpeed(){ return console.log(speed); } function accelerate(){ speed +=10 return speed; } function decelerate(){ speed -=10 return speed; } function getStatus(){ return console.log(speed===0?'stop':'running'); } return { setSpeed:setSpeed, getSpeed:getSpeed, accelerate:accelerate, decelerate:decelerate, getStatus:getStatus, } }()); Car.setSpeed(30); Car.getSpeed(); //30 Car.accelerate(); Car.getSpeed(); //40; Car.decelerate(); Car.decelerate(); Car.getSpeed(); //20 Car.getStatus(); // 'running'; Car.decelerate(); Car.decelerate(); Car.getStatus(); //'stop'; Car.speed(); //error
Write a function using setTimeout to simulate the function of setInterval
Code:
var i=0; function intv(){ setTimeout(function(){ console.log(i++); intv(); },1000); } intv();
Write a function to calculate the minimum time granularity of setTimeout
Code:
function getmin(){ var i = 0; var start = Date.now(); var clock = setTimeout(function(){ i++; if(i === 1000){ clearTimeout(clock); var end = Date.now(); console.log((end-start)/i) } clock = setTimeout(arguments.callee,0) },0) } getmin()
What is the output result of the following code? Why?
var a = 1; setTimeout(function(){ a = 2; console.log(a); }, 0); var a ; console.log(a); a = 3; console.log(a);
The output result of this code is 1;3;2, because a setTimeout is set in the code, then the browser will insert the code into the task queue at the appropriate time. If this time is set If it is 0, it means that it will be inserted into the queue immediately, but it will not be executed immediately. You still have to wait for the previous code to be executed, so you have to wait until all the code is executed before executing setTimeout(function(){a = 2;console.log(a); }, 0);.
What is the output result of the following code? Why?
var flag = true; setTimeout(function(){ flag = false; },0) while(flag){} console.log(flag);
will not output the result because setTimeout(function(){flag = false;},0) will It will be run after all the code has been executed. The initial value of ``flag is true, so while will continue to loop, and console.log(flag) will not be accessed. However, due to the loop protection function of some browsers, It is also possible that the output is true```.
What is the output of the following code? How to output delayer: 0, delayer:1... (use closure to implement)
for(var i=0;i<5;i++){ setTimeout(function(){ console.log('delayer:' + i ); }, 0); console.log(i); }
Code:
for(var i=0;i<5;i++){ (function(i){ setTimeout(function(){ console.log('delayer:' + i ); }, 0); })(i) console.log(i); }
Brain-burning question
What is the result of the following console.log? Why?
function fn(a,b) { console.log(b); return { fn:function(c){ return fn(c,a); } }; } var a = fn(0); a.fn(1); a.fn(2); a.fn(3); var b = fn(0).fn(1).fn(2).fn(3); var c = fn(0).fn(1); c.fn(2); c.fn(3);
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Related reading:
Simple CSS3 click response animation case
How to use python to determine image similarity
The above is the detailed content of JS closures and timers. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

The timer expression is used to define the execution plan of the task. The timer expression is based on the model of "execute a task after a given time interval". The expression usually consists of two parts: an initial delay and a time interval.
