首页 > 解决方案 > 如何删除javascript中的函数

问题描述

const resumeInfinity = () => {
  window.speechSynthesis.resume();
  const timeoutResumeInfinity = setTimeout(resumeInfinity, 1000);
  console.log(timeoutResumeInfinity);
}
      
utterThis.onstart = () => {
 resumeInfinity();
};

需要 ( resumeInfinity) 函数在 SpeechSynthesi 之后停止工作

标签: javascript

解决方案


为避免错误消息,resumeInfinity is not a function您不应将其删除,而是将其设置为空函数。但是正如您所定义resumeInfinity的那样,const您无法更改该功能。

因此,您可以将其更改为:

let resumeInfinity = () => {
   // ... your code
}

然后稍后将其更改为空函数resumeInfinity = () => {} 但是您需要记住,如果该原始函数作为回调传递给其他地方(例如这里setTimeout(resumeInfinity, 1000)),则此回调仍将引用旧函数。

因此,更好的解决方案是检查该函数是否仍然有效才能执行,否则提前退出。

const resumeInfinity = () => {
  if( /* some check if isn't valid to call that function anymore */ ) {
     return
  }
  window.speechSynthesis.resume();
  const timeoutResumeInfinity = setTimeout(resumeInfinity, 1000);
  console.log(timeoutResumeInfinity);
}

但上述所有这些解决方案实际上只是一种解决方法,因为如果您的应用程序的逻辑是正确的,那么这种情况就永远不会发生。所以需要做这样的事情表明你更有可能需要考虑重组你的代码。

如果只是要停止超时,那么您需要调用clearTimeout(timeoutResumeInfinity),并timeoutResumeInfinity在您知道 SpeechSynthesi 完成的地方提供。


推荐阅读