Recursive Call Loop Questions for jstimer Processing

Asked 1 years ago, Updated 1 years ago, 20 views

When making timers with js, I think it is common to make them with recursive calls as shown below.
I doubt that this will work.

function timers(){
     timerId = setTimeout(function(){
          // Processing
         timers();
     }, 10);
}

function stoptimers() {
     clearTimeout(timerId);
}

I understand that the timer stops because the timer ID entered in the variable timerId is clearTimeout as an argument, but if there is an infinite loop in the recursive call, the processing to the right of = has not been completed, so the substitution will not be performed.I am not sure when the variable timerId has a value.

Please let me know if you know.

javascript

2022-09-30 17:07

2 Answers

There are no recursive calls (?) at the time of assignment, but they are simply held as functional expressions (called and executed after a specified period of time), so the assignment can be completed even if the call process is not complete.

I doubt if this is a recursive call because the function expression is simply a function object, not executed when it is passed as an argument and replaced by the result.
Maybe it's like a queue.
[function(){timers();}, function(){another function or ();}, function(){timers();}/* *Not stacked at the same time.Next (i.e., future) guy */,...] // Queue guy
It is stored in a row as shown in , and is called from the beginning and consumed.
I think it will run with an image like this


2022-09-30 17:07

The easiest way to understand is to actually run the setTimeout function in your browser.Try executing the following code on the Google Chrome console.

setTimeout(function() {console.debug('done');},1000)

The number displayed immediately after execution is the return value of the setTimeout function, timeoutID.A second later, "done" should appear on the console.

A function in javascript is called a first-class object and can be substituted for a variable or an argument or return value for a function.The first argument of the setTimeout function is a function.The source in the example defines an unknown function and passes it as an argument on the spot, so it may feel complicated if you are not used to it.

You can easily understand it by looking at the following sources (equivalent to processing).

function timers(){
    timerId = setTimeout(next,10);
    // ↑ Not calling the next function, but passing the function definition
    // If you want to call the next function, you need parentheses like next()
}

function next() {
    console.debug('next');
    timers();
}
....


2022-09-30 17:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.