Recursion and setTimeout

problem description

creates a recursive function A that calls itself every 5 seconds, and there is a function B that websocket will push messages every once in a while. Function A will execute An in the callback of B, that is, when B pushes, but the B function will be pushed again less than 5 seconds after the first execution, so function A will execute recursively superimposed at this time.

the environmental background of the problems and what methods you have tried

related codes

/ / Please paste the code text below (do not replace the code with pictures)

  (function(arr) {
    var i = 0,
    len = arr.length;
    clearTimeout(self.setVar);
    (function setColor() {
      self.setVar = setTimeout(function() {
        
        if (i < len-1) {
          if (i > 0) {
            arr[i - 1].borderWidth = 0;
          }
          arr[i].borderColor = "45,215,16";
          arr[i].borderWidth = 2;
          console.log(i,"----")
          var aaa = window.localStorage.getItem("arrDatas");
          console.log(aaa,"=========PPPPPP+");
          i = i + 1;
          // clearTimeout(self.setVar);
          setColor();
          // clearTimeout(self.setVar);
        } else if(i===len-1){
          var bbb = window.localStorage.getItem("arrDatas");
          console.log(bbb,"==");
          arr[i].borderColor = "45,215,16";
          arr[i].borderWidth = 2;
          arr[i-1].borderWidth = 0;
          i = i+1;
          
          setColor();
        }else{
          arr[i-1].borderWidth = 0;
          i = 0;
          // clearTimeout(self.setVar);
          setColor();
        }
      }, 5000);
     
    })(i);
  })(nodeExample);

what result do you expect? What is the error message actually seen?

topic description

I tried to clear the timer, but it didn"t work

sources of topics and their own ideas

related codes

/ / Please paste the code text below (do not replace the code with pictures)

what result do you expect? What is the error message actually seen?

problem description

the environmental background of the problems and what methods you have tried

related codes

/ / Please paste the code text below (do not replace the code with pictures)

what result do you expect? What is the error message actually seen?

May.14,2021

is the position you cleared a little far

 clearTimeout(self.setVar);
    (function setColor() {
      self.setVar = setTimeout(function() {

changing it to this way will not result in multiple setTimeout

(function setColor() {
  clearTimeout(self.setVar);
  self.setVar = setTimeout(function() {
Menu