繁体   English   中英

未捕获的类型错误...不是函数

[英]uncaught type error… is not a function

我正在控制台中练习此简单的倒数计时功能,当我完成编写并按Enter键后,代码就会工作,但是当我尝试再次调用它时(键入countDown(); ),控制台会显示以下错误消息:

“未捕获的TypeError:countDown不是函数”。

我将函数保存在变量countDown ,当我调用该函数时,只需键入countDown(); 我检查了没有输入错误。 我做错了什么,代码如下:

var timeLeft = 10;
var countDown = setInterval(function(){
  timeLeft--;
  console.log(timeLeft);
  if(timeLeft === 0){
    clearInterval(countDown)
    console.log("count down completed")
  }
} ,1000);

我将函数保存在变量countDown中

不,你救的_The结果setInterval的变量。

setInterval返回计时器ID,而不是函数。

如果要将函数保存在变量中,则实际上需要将函数保存在变量中。

我认为您应该在setInterval之外声明函数,我提供了以下示例供您参考:

var timeLeft  = 10;
var countDown  = setInterval(timer, 1000 );

function timer() {
   console.log(timeLeft);
   if (timeLeft < 1) {
      console.log('Count down completed'); 
      clearInterval(countDown);
      return;         
   } 
   timeLeft  -= 1;
}

暂无
暂无

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

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