【问题标题】:How to stop nested timeOut with same names?如何停止具有相同名称的嵌套超时?
【发布时间】:2019-08-07 06:40:38
【问题描述】:

我正在尝试使用具有相同名称的嵌套timeOut,这实际上就像一个循环,而不是完全一样。 我尝试使用这个例子:

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

来自这个link。 正如您在此链接中看到的,我不能使用interval 和loop。

这是我的实际代码:

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);

我的输出:

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

我也看到了这个link,但不是我的情况。

任何人都可以做点什么让我完全停止x吗?
提前致谢。

【问题讨论】:

  • 你需要在 clearTimeout 之后从函数中 return 否则会在几行之后创建新的超时

标签: javascript settimeout cleartimeout


【解决方案1】:

你不需要超时引用,因为如果在函数内部引用无效,因为超时被调用。然后你需要停下来才能返回。

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);

【讨论】:

    【解决方案2】:

    因为当你clearTimeout 时,你不会被return 阻止。因此,您的超时将使用x = setTimeout(run, 800); 设置另一个超时。你需要做的就是return你的clearTimeout(x)来停止你的超时功能。

        return clearTimeout(x);
    

    在您的代码中,我看不出您需要清除超时的任何理由。超时只运行一次。所以如果你执行它。完成了。

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 1970-01-01
      • 2013-11-11
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多