繁体   English   中英

clearInterval() 在 typescript 中使用时抛出“没有重载匹配此调用”

[英]clearInterval() throwing 'No overload matches this call' when used in typescript

我正在尝试编写一个 setInterval function(按预期工作),但是一旦 this.attempts 达到 this.retryTimes 的级别,它就应该被清除。 当我尝试如下所示调用 clearInterval() 时,出现以下错误:

No overload matches this call.
  Overload 1 of 2, '(intervalId: Timer): void', gave the following error.
    Argument of type '() => void' is not assignable to parameter of type 'Timer'.
      Type '() => void' is missing the following properties from type 'Timer': ref, unref
  Overload 2 of 2, '(handle?: number): void', gave the following error.
    Argument of type '() => void' is not assignable to parameter of type 'number'.
const retryLoop = () => {
      if (this.shouldRetry) {
        this.attemptRetry();
        this.showError = true;
      }
      this.attempts = this.attempts + 1;
    };
    const stopRetry = () => {
      clearInterval(retryLoop);
    }
      setInterval(retryLoop, 5000);
      if (this.attempts > this.retryTimes) {
        clearInterval(stopRetry)
      }
    }

为了清除间隔(使用clearInterval ),您需要从setInterval获取回报,您几乎拥有它:

function something() {
    const retryLoop = () => {
        if (this.shouldRetry) {
            this.attemptRetry();
            this.showError = true;
        }
        this.attempts = this.attempts + 1;
    };
    const stopRetry = setInterval(retryLoop, 5000);
    if (this.attempts > this.retryTimes) {
        clearInterval(stopRetry);
    }
}

您可以忽略function something() { line.. 最后只有一个不匹配的右括号,所以我将它包装起来(在其上运行自动格式化程序)

clearInterval(xxxxx):这里 xxxx 应该是setInterval本身,而不是 function ( retryLoop )。


w3school 链接: https://www.w3schools.com/jsref/met_win_clearinterval.asp

clearInterval() 方法清除使用 setInterval() 方法设置的计时器。

myVar = setInterval("javascript function", milliseconds);

clearInterval(myVar);


将计时器从“5000”更改为“1000”只是为了快速执行。

 let attempts = 1; const retryTimes = 10; const retryLoop = () => { console.log("retry no: "+attempts) attempts = attempts + 1; if (attempts > retryTimes) { console.log("---- ending retry ----") clearInterval(attemptRetry); } }; var attemptRetry = setInterval(retryLoop, 1000);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM