Home Web Front-end HTML Tutorial JS closures and timers

JS closures and timers

Mar 08, 2018 pm 03:10 PM
javascript timer

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 );  //
Copy after login

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 );  //
Copy after login

Method two:

var fnArr = [];
for (var i = 0; i < 10; i ++) {
(function(n){
fnArr[i] = function(){
return n;
}
})(i)
};
console.log( fnArr3 )
Copy after login

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(); // &#39;running&#39;;
Car.decelerate();
Car.decelerate();
Car.getStatus();  //&#39;stop&#39;;
//Car.speed;  //error
Copy after login

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?&#39;stop&#39;:&#39;running&#39;);
}
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(); // &#39;running&#39;;
Car.decelerate();
Car.decelerate();
Car.getStatus();  //&#39;stop&#39;;
Car.speed();  //error
Copy after login

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();
Copy after login

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()
Copy after login

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);
Copy after login

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);
Copy after login

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(&#39;delayer:&#39; + i );
}, 0);
console.log(i);
}
Copy after login

Code:

for(var i=0;i<5;i++){
(function(i){
setTimeout(function(){
console.log(&#39;delayer:&#39; + i );
}, 0);
})(i)
console.log(i);
}
Copy after login

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);
Copy after login

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!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

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 forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

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

What is java timer expression What is java timer expression Dec 27, 2023 pm 05:06 PM

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.

See all articles