Pouria Moosavi
Pouria Moosavi

Reputation: 730

How to stop nested timeOut with same names?

I am trying to use nested timeOut with the same names which is actually works like a loop, not exactly like it. I try to use this example:

let i = 1;
setTimeout(function run() {
  func(i);
  setTimeout(run, 100);
}, 100);

from this link. As you see in this link, I cant use interval and loop.

Here is my actual code:

let i = 0;
let x = setTimeout(async function run() {
  if(i == 2) {
    // I want to stop my x here completly
    console.log(i)
    clearTimeout(x);
  }
  try {
    //some code here e.g:
    console.log(10)
  } catch (err) {
    //some other code here e.g:
    console.log(err)
  }
  i++;
  x = setTimeout(run, 800);
}, 800);

And my output:

10
10
2
10
10
... //never stops

I also saw this link, but it is not my case.

Could any body please do something so that I can stop x completely?
Thanks in advance.

Upvotes: 0

Views: 365

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

You need not the timeout reference, because if inside of the function the reference is invalid, because the timeout is called. Then you need to stop just to return.

let i = 0;
setTimeout(async function run() {
  if (i == 2) {
    console.log(i)
    return
  }
  try {
    //some code here e.g: 
    console.log(10)
  } catch (err) {
    //some other code here e.g:
    console.log(err)
  }
  i++;
  setTimeout(run, 800);
}, 800);

Upvotes: 3

Tien Duong
Tien Duong

Reputation: 2595

Because when you clearTimeout you don't stop it by return. So your timeout will set another timeout with x = setTimeout(run, 800);. All you need to do is return your clearTimeout(x) to stop your timeout function.

    return clearTimeout(x);

In your code, I don't see any reason you need to clear timeout. Timeout run only once time. So if you execute it. It is done.

Upvotes: 2

Related Questions