Example Analysis of js Recursion and Timer

  • 2021-07-16 01:16:05
  • OfStack

Recursion: A function is formed by calling itself;

First of all, the previous example:


Function factorial(num){
 if(num<=1){
 return 1;
 }else{
 return num*factorial(num-1);
 }
}

This is a classic recursive factorial function, but in js, calling this function may cause some errors: for example, the following code


var anotherFactorial = factorial;
factorial = null;
alert(anotherFactorial)//  Error 

The above code first saves the factorial () function in the variable anotherFactorial, and then sets the factorial variable to null, resulting in only one reference to the original function. But the next call to anotherFactioral () will result in an error because the factorial function must be executed and factoial is no longer a function. In this case, arguments. callee can solve this problem.

arguments. callee is a pointer to an executing function, so it can be used to make recursive calls to functions.

For example:


function factorial (num){
 if(num){
 return 1;
 }else{
 return num*arguments.callee;
 }
}

arguments. callee Advantages:

1. You can ensure that no matter how you call the function, there will be no problem. Therefore, when writing recursive functions, it is safer to use argments. callee than to use function names.

Note: If it is invalid in strict mode, it will report an error

Writing in strict mode:


var factorial = (function f(){
 if(num<1){
 return 1;
 }else{
 return num*f(num-1);
 }
})

2. Used in conjunction with a timer:

js is a single-threaded language, but it allows you to schedule code execution at specific times by setting timeout calls and interval times. The former executes code after a specified time, while the latter executes code once every specified time.

Parameters: Code to execute and time in milliseconds


// Passing strings is not recommended , Passing strings may cause performance loss  
setTimeout("alter('hello word')", 1000);
// Recommended way 
setTimeout(function(){
 alter("Hello world");
},1000)
setInterval(function(){
 alter("Hello world");
},1000)

Note: End

Timeout calls are executed in global scope, so the value of this in the function points to the window object in non-strict mode and undefined in strict mode;

In practical application:

Using timeout calls to simulate intermittent calls is the best mode. In the development environment, real intermittent calls are rarely used, because the last intermittent call may start between the first intermittent call.


var num = 0, max = 0;
function incrrmentNumber{
 num++;
 if(num < max){
 setTimeout(incrrmentNumber,500);
 }else{
 alert("Done");
 }
}
setTimeout(incrrmentNumber,500);

If you use timeout calls as above, you can avoid this 1 point. So don't use intermittent calls;


Related articles: