【问题标题】:setTimeout causing Uncaught TypeError: number is not a functionsetTimeout 导致 Uncaught TypeError: number is not a function
【发布时间】:2015-02-10 23:42:50
【问题描述】:

所以我在函数之外声明空白变量。

//To be Timeouts
var progressionTimer;
var nextTimer; 
var cycleTimer;

然后在函数内

progressionTimer = setTimout(loadNextFunction, 2000);
progressionTimer();

nextTimer = setTimeout(loadOutsideFunction, 2000);
nextTimer();

//etc

但是每次调用其中一个声明时

nextTimer();

我在 chrome/firefox/etc 中的控制台充满了这个

Uncaught TypeError: number is not a function

它完全按预期运行,并且 clearTimeout 正常工作,但控制台错误让我感到沮丧,任何人都可以在不失去功能的情况下解决这个问题并且仍然有 clearTimeout 工作吗?

【问题讨论】:

  • 因为 nextTimer 不是一个函数,它是一个超时 id,你可以传递给 clearTimout 来清除它。

标签: javascript jquery settimeout typeerror cleartimeout


【解决方案1】:

setTimeout 返回一个处理程序,一个允许您引用超时的 ID,以便您可以使用 clearTimeout 清除它,这是一个数字。

没有返回一个可以执行的函数,这就是问题所在,你正在尝试执行setTimeout的返回值

nextTimer = setTimeout(loadOutsideFunction, 2000);
nextTimer(); // not a function, but a number referencing the timeout ?

clearTimeout(nextTimer); // works just fine

【讨论】:

  • 谢谢!我的印象是我必须调用 setTimeout。所以现在我刚刚删除了 nextTimer();并且它的所有功能都没有问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-15
  • 2021-12-16
  • 2018-04-20
  • 2017-04-13
相关资源
最近更新 更多