Introduction to JavaScript – function (II)

Time:2021-11-29

Introduction to JavaScript – function (II)

Recursive function

  • What is a recursive function?
    Recursion is simply understood as calling itself in the body of a function.
//We might do this when we find a factorial of 10
    //Write a loop
    var total = 1
    for(var i=10; i>=1; i++){
        total *= i ;
    }
    Such a for loop is simple and direct... Everyone can write
    However, we can write a function, recursive call
    //Recursive function
    function jiecheng( n ){
        if ( 1===n) return 1
        return n*jiecheng(n-1)
    }
    //Call recursive function
    var total = jiecheng(10)

PS: Although the results of the two different methods are the same, there are still differences. Recursion does not traverse every number through the for loop, and the amount of code becomes less, which looks a little tall.

  • In fact, when calling recursively, it is executed according to the specific of return. Because return returns to the caller only when a specific value is encountered.
  • Then, when calling, there will be a ‘stack’ data structure (first in, last out, last in, first out) to store the state of each call. Until a state with specific values is encountered, it will be returned to the caller layer by layer. The final value is the value you want.

Disadvantages of recursion

  • Each time you call yourself, you are actually occupying memory and resources.

closure

  • What is a closure?
    Let’s first review that in Es5, we can access the variable defined by VaR, whether it is defined in the code block or the local variable in the for loop, which is called the global variable. If we use VaR to define a variable in a function, it is a local variable, which can only be used internally.
//Define global variables
    var a =1;

    //Function body definition variable
    function fun(){
        var b =1;
    }

    //Define variables in code blocks
    {
        var c = 1
        {
            var d = 'rainbow'
        }
        
    }
    //Variables in the for function
    for( var i = 0 ; i<10 ;i++){
        console.log(i)
    }
        console.log( a , c , d , i )//1 1 "rainbow" 10
        console.log(b)//error

PS: it can be seen from the above code that in JavaScript, all variables are global variables except the variables in the method body. What should we do if we want to access the variables in the function??
At this time, we will use closures.

  1. Customize a method in the function to return the local variables defined by the function.
  2. When calling, we first call the outer function to get a function body, and then call again to get the variables of the inner members of outer.
function outer(){
        var num = 10;

        funtion inner(){
            console.log(num)
        }
        return inner;
    }

    var fun = outer()
    fun()//10

    perhaps

    function outer() {

        var age = 20;

        Return function() {// anonymous function
            return age;
        }
    }
    var age1 = outer();
    console.log(age1())//20

Conclusion: closure is to define a function inside a function and return the private attributes in function to the outside through this internal function.
characteristic:

  1. You can read variables inside a function through closures
  2. Every time the outermost method is called, it actually reopens a piece of memory space. Because the returned inner method is not closed and always occupies memory, we can manually close outer = null
  3. Variables defined in outer and member variables obtained through closures are actually static variables. As mentioned in point 2, variables still exist in memory and are not actively released.

Disadvantages of closures

  • Similar to recursion, it always occupies memory resources, which may lead to memory leakage.

Maybe I didn’t say enough. Let’s look at the boss’s article

Thoroughly understand closures
https://www.cnblogs.com/itjeff/p/10106855.html
Teacher Ruan Yifeng’s
http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html

Callback function

The callback function has a more compelling name – handle. We just need to know that there is such an official name. In the future, when we interview or communicate, we won’t be unable to understand what this is.
The simple understanding is, take a function as an argument. Then this function is the callback function.
Why is it called callback?
That’s because when you execute a method, you can’t predict or determine what results will be. You mustCall this function again(that is, the parameters passed) to obtain specific results.

function fun(callback){
        console.log(callback)
    }
    //Take a method as an argument

    function say (value) {
    alert(value);
    }
    alert(say);
    alert(say('hi js.'));

PS: callback function application scenarios are mostly used when writing components using JS. In particular, many component events need the support of callback functions.

Built in function

In fact, our JS class library provides many functions, such as console. Log (), alert () and so on. However, before learning object-oriented, let’s mainly learn about two built-in functions, timerSetTimeout and setinterval

//Method of use
    setTimeout(callback,delay);
    setInterval(callback,delay);

    function callback(){
        console.log('rainbow');
    }

    var delay = 1*1000;

    //Explain
    Callback: the method to be executed by the timer
    Delay: the interval at which the timer executes the method. Unit: ms

Differences between setTimeout and setinterval

  • SetTimeout can only be executed once, while setinterval is always executed.

So how to stop the timer?
Each timer will return a timer ID, which is stored in the process pool. We receive its ID and clear it

//Receive ID
    var id1 = setTimeout(callback,delay);
    var id2 = setInterval(callback,delay);

    //Turn off the timer
    clearTimeout(id1)
    clearInterval(id2)

ps:

  1. Closing the timer, cleartimeout or clearinterval can close each other’s ID because they share a timer ID poor.
  2. The delay parameter is not very accurate because it is related to the rotation of the time slice. To learn more, you can learn about the operating system, processes and threads.

In fact, when learning timers, we should understand that there are onlySingle threadMoreover, there is no asynchronous operation in theory. What you say is analog asynchronous, so you need to understand a problem calledTask queueSomething.
Here, let’s talk about the three tasks. In fact, there are still many tasks:

  • Rendering queue: such as browser rendering and IE hasLayout
  • Event queue: for example, click the event onclick
  • Timer queue: it will be executed after the main program is executed
    These are executed in a certain order, rendering queue – > event queue – > timer queue, so the timer is like an outcast. Everything can only be owned last, which shows why you can’t set the delay time so accurately.

Thank you for reading this essay. I have little knowledge. What I said in many places is not very in-depth and vulgar. Forgive me

Recommended Today

On the mutation mechanism of Clickhouse (with source code analysis)

Recently studied a bit of CH code.I found an interesting word, mutation.The word Google has the meaning of mutation, but more relevant articles translate this as “revision”. The previous article analyzed background_ pool_ Size parameter.This parameter is related to the background asynchronous worker pool merge.The asynchronous merge and mutation work in Clickhouse kernel is completed […]