setTimeout 导致未捕获的类型错误:数字不是一个函数

setTimeout causing Uncaught TypeError: number is not a function

本文关键字:函数 一个 数字 错误 类型 setTimeout      更新时间:2023-09-26

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

//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 工作的情况下解决这个问题吗?

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

返回可以执行的函数,这就是问题所在,您正在尝试执行 setTimeout 的返回值

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