JS closures and timers

php中世界最好的语言
Release: 2018-03-08 15:10:29
Original
2027 people have browsed it

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(); // 'running';
Car.decelerate();
Car.decelerate();
Car.getStatus();  //'stop';
//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?'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
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('delayer:' + i );
}, 0);
console.log(i);
}
Copy after login

Code:

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

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!