Today, I did a small project and found a problem. I used setInterval() to loop a function. The effect was fine, but I had a problem with the speed of setInterval()

Suppose I change setInterval() to a variable, and it works, but if I change the amount, it doesn’t change the speed, why, if I go to Google, setInterval() it only reads the variable once, and it keeps executing

let n = 0
let n = 1000
let id = setInterval(() = > {
  n += 1
  output.innerText = n
  console.log(n)
  if(n>=10) {window.clearInterval(id)
  }
},n)
Copy the code

Changing the value of n is not feasible

I then looked up and found a method that would satisfy me, setTimeout(), whose magic is that it only executes once, so modifying the variable works

let n = 0
let a = 1000
let id = setTimeout(function(){
  n += 1
  output.innerText = n
},a)
Copy the code

If you look at the code above, it can change the variable and change the speed, but the problem is again, it doesn’t loop

So if you think about recursion, you’re going to use a function called delay recursion

let n = 0
let id = setTimeout(function(){
  n += 1
  output.innerText = n
  setTimeout(fn, 500)},500)

Copy the code

Another question. How do we get him to stop

let n = 0
let id = setTimeout(function(){
  n += 1
  output.innerText = n
  if(n < 10) {setTimeout(fn, 500)}// Clear is not needed here either, since setTimeout is called only once
},500)
Copy the code

This sentiment is good ah, also need not write clear, he only once do not call no longer execute

Note that the callback function cannot be anonymous either, because it is called when a callback is needed