Home Web Front-end JS Tutorial An explanation of JS timer and closure issues

An explanation of JS timer and closure issues

May 21, 2018 am 11:19 AM
javascript timer Closure

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]() );
Copy after login
方法二:    var fnArr = [];    for (var i = 0; i < 10; i ++) {
      (function(){        var a = i;            //取消参数,还是运用闭包将i赋值给a
        fnArr[i] =  function(){            return a;
        };
      } )();
    }    console.log( fnArr[5]() );
Copy after login

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(&#39;running&#39;);
    }    if(speed===0){      console.log(&#39;stop&#39;);
    }
  }  
  return {    setSpeed:setSpeed,    getSpeed:getSpeed,    accelerate:accelerate,    decelerate:decelerate,    getStatus:getStatus,
  };
  
})();
Copy after login
Car.setSpeed(30);
Car.getSpeed(); //30Car.accelerate();
Car.getSpeed(); //40;Car.decelerate();
Car.decelerate();
Car.getSpeed(); //20Car.getStatus(); // &#39;running&#39;;Car.decelerate(); 
Car.decelerate();
Car.getStatus();  //&#39;stop&#39;;//Car.peed;  //error
Copy after login

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();              //执行父函数
Copy after login

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

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

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

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(&#39;delayer:&#39; + 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(&#39;delayer:&#39; + i );    
    }    return set(i);
  })(i); 
}
Copy after login

The result is:

"delayer:0""delayer:1""delayer:2""delayer:3""delayer:4"
Copy after login

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!

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)

What is the meaning of closure in C++ lambda expression? What is the meaning of closure in C++ lambda expression? Apr 17, 2024 pm 06:15 PM

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.

What are the advantages and disadvantages of closures in C++ functions? What are the advantages and disadvantages of closures in C++ functions? Apr 25, 2024 pm 01:33 PM

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.

How to implement closure in C++ Lambda expression? How to implement closure in C++ Lambda expression? Jun 01, 2024 pm 05:50 PM

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.

Solve the memory leak problem caused by closures Solve the memory leak problem caused by closures Feb 18, 2024 pm 03:20 PM

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,

The role of golang function closure in testing The role of golang function closure in testing Apr 24, 2024 am 08:54 AM

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.

Chained calls and closures of PHP functions Chained calls and closures of PHP functions Apr 13, 2024 am 11:18 AM

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 Golang performance The impact of function pointers and closures on Golang performance Apr 15, 2024 am 10:36 AM

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.

How are closures implemented in Java? How are closures implemented in Java? May 03, 2024 pm 12:48 PM

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.

See all articles