search
HomeWeb Front-endHTML TutorialJS closures and timers

JS closures and timers

Mar 08, 2018 pm 03:10 PM
javascripttimer

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(); // &#39;running&#39;;
Car.decelerate();
Car.decelerate();
Car.getStatus();  //&#39;stop&#39;;
//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?&#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

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

Code:

for(var i=0;i<5;i++){
(function(i){
setTimeout(function(){
console.log(&#39;delayer:&#39; + 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!

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
Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

Explain the importance of using consistent coding style for HTML tags and attributes.Explain the importance of using consistent coding style for HTML tags and attributes.May 01, 2025 am 12:01 AM

A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

How to implement multi-project carousel in Bootstrap 4?How to implement multi-project carousel in Bootstrap 4?Apr 30, 2025 pm 03:24 PM

Solution to implement multi-project carousel in Bootstrap4 Implementing multi-project carousel in Bootstrap4 is not an easy task. Although Bootstrap...

How does deepseek official website achieve the effect of penetrating mouse scroll event?How does deepseek official website achieve the effect of penetrating mouse scroll event?Apr 30, 2025 pm 03:21 PM

How to achieve the effect of mouse scrolling event penetration? When we browse the web, we often encounter some special interaction designs. For example, on deepseek official website, �...

How to modify the playback control style of HTML videoHow to modify the playback control style of HTML videoApr 30, 2025 pm 03:18 PM

The default playback control style of HTML video cannot be modified directly through CSS. 1. Create custom controls using JavaScript. 2. Beautify these controls through CSS. 3. Consider compatibility, user experience and performance, using libraries such as Video.js or Plyr can simplify the process.

What problems will be caused by using native select on your phone?What problems will be caused by using native select on your phone?Apr 30, 2025 pm 03:15 PM

Potential problems with using native select on mobile phones When developing mobile applications, we often encounter the need for selecting boxes. Normally, developers...

What are the disadvantages of using native select on your phone?What are the disadvantages of using native select on your phone?Apr 30, 2025 pm 03:12 PM

What are the disadvantages of using native select on your phone? When developing applications on mobile devices, it is very important to choose the right UI components. Many developers...

How to optimize collision handling of third-person roaming in a room using Three.js and Octree?How to optimize collision handling of third-person roaming in a room using Three.js and Octree?Apr 30, 2025 pm 03:09 PM

Use Three.js and Octree to optimize collision handling of third-person roaming in the room. Use Octree in Three.js to implement third-person roaming in the room and add collisions...

See all articles

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment