An explanation of JS timer and closure issues
This article explains the JS timer and closure issues.
What is a closure? What is its role?
If a function has permission to access variables inside another function, then this internal function can be called a closure.
Function:
Be able to access local variables inside another function
Always keep the values of these variables in memory
What is the role of setTimeout 0
It is equivalent to placing this code at the end of the execution code and executing it immediately. This code will be executed immediately after all the codes have been executed.
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 ++) { (function(i){ fnArr[i] = function(){ return i; }; } )(i); } console.log( fnArr[3]() );
方法二: var fnArr = []; for (var i = 0; i < 10; i ++) { (function(){ var a = i; //取消参数,还是运用闭包将i赋值给a fnArr[i] = function(){ return a; }; } )(); } console.log( fnArr[5]() );
Use a closure to encapsulate a car object. You can obtain the car status in the following ways
var Car = (function(){ var speed = 0 ; function setSpeed(n){ speed = n ; } function getSpeed(){ console.log(speed) ; } function accelerate(){ speed += 10 ; } function decelerate(){ speed -= 10 ; } function getStatus(){ if(speed>0){ console.log('running'); } if(speed===0){ console.log('stop'); } } return { setSpeed:setSpeed, getSpeed:getSpeed, accelerate:accelerate, decelerate:decelerate, getStatus:getStatus, }; })();
Car.setSpeed(30); Car.getSpeed(); //30Car.accelerate(); Car.getSpeed(); //40;Car.decelerate(); Car.decelerate(); Car.getSpeed(); //20Car.getStatus(); // 'running';Car.decelerate(); Car.decelerate(); Car.getStatus(); //'stop';//Car.peed; //error
Write a function using setTimeout to simulate the function of setInterval
var a= 0;function intv(){ setTimeout(function (){ console.log(a++); intv(); //在子函数内调用父函数形成循环 },1000); //1秒后执行} intv(); //执行父函数
Write a function to calculate the minimum time granularity of setTimeout
function num(){ var i =0; var start= Date.now(); //获取当前时间毫秒赋值为start var clock = setTimeout(function(){ //为匿名函数设置定时器立即执行 i++; //i每次+1 if(i === 1000){ //条件为i执行1000次 clearTimeout(clock); //则取消定时器 var end = Date.now(); //获取执行后时间毫秒赋值为end console.log((end-start)/i); //执行后时间-执行前时间再除以次数输出结果 } else{ clock = setTimeout(arguments.callee,0) //不到1000次再次执行此匿名函数 } },0) } num();
What is the output result of the following code? Why?
var a = 1; setTimeout(function(){ a = 2; console.log(a); }, 0); //这里使用setTimeout 0,此代码最后执行,所以最后输出2var a ;console.log(a); //输出为1a = 3;console.log(a); //输出为3输出结果为:132
What is the output result of the following code? Why?
var flag = true; setTimeout(function(){ flag = false; },0) //此代码放置最后while(flag){} //flag为true,代码在这里陷入无限循环 console.log(flag);
The output result is:
Empty, trapped in an infinite loop
What is the output of the following code? How to output delayer: 0, delayer:1... (implemented using closure)
for(var i=0;i<5;i++){ setTimeout(function(){ console.log('delayer:' + i ); }, 0); //此代码放置最后执行,i已变为5,输出delayer:5; console.log(i); //循环输出 0,1,2 ,3 ,4} for(var i=0;i<5;i++){ (function(i){ function set(i){ console.log('delayer:' + i ); } return set(i); })(i); }
The result is:
"delayer:0""delayer:1""delayer:2""delayer:3""delayer:4"
This article explains the JS timer and closure issues, and more For more related content, please pay attention to php Chinese website.
Related recommendations:
How to use front-end js to modularize require.js
A picture implemented with CSS Completed button example
Related knowledge about AJAX ASP/PHP request example
The above is the detailed content of An explanation of JS timer and closure issues. 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

In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

Title: Memory leaks caused by closures and solutions Introduction: Closures are a very common concept in JavaScript, which allow internal functions to access variables of external functions. However, closures can cause memory leaks if used incorrectly. This article will explore the memory leak problem caused by closures and provide solutions and specific code examples. 1. Memory leaks caused by closures The characteristic of closures is that internal functions can access variables of external functions, which means that variables referenced in closures will not be garbage collected. If used improperly,

Go language function closures play a vital role in unit testing: Capturing values: Closures can access variables in the outer scope, allowing test parameters to be captured and reused in nested functions. Simplify test code: By capturing values, closures simplify test code by eliminating the need to repeatedly set parameters for each loop. Improve readability: Use closures to organize test logic, making test code clearer and easier to read.

Yes, code simplicity and readability can be optimized through chained calls and closures: chained calls link function calls into a fluent interface. Closures create reusable blocks of code and access variables outside functions.

The impact of function pointers and closures on Go performance is as follows: Function pointers: Slightly slower than direct calls, but improves readability and reusability. Closures: Typically slower, but encapsulate data and behavior. Practical case: Function pointers can optimize sorting algorithms, and closures can create event handlers, but they will bring performance losses.

Closures in Java allow inner functions to access outer scope variables even if the outer function has exited. Implemented through anonymous inner classes, the inner class holds a reference to the outer class and keeps the outer variables active. Closures increase code flexibility, but you need to be aware of the risk of memory leaks because references to external variables by anonymous inner classes keep those variables alive.
