JavaScript 'countdown' 不是定义错误

javascript 'countdown' is not defined error

本文关键字:定义 错误 countdown JavaScript      更新时间:2023-09-26

我不断得到"倒计时未定义"这一行

  var timeout = setTimeout('countdown()',1000);

它应该每秒循环一次function countdown()。 我该如何解决这个问题?

function countdown() {
var until = $('.time-elapsed').attr('data-time');
var nextmonth = new Date(until);
var now = new Date();
var timeDiff = nextmonth.getTime() - now.getTime();
if(timeDiff <=0) {
var nextmonth = new Date(until);
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days =  Math.floor(hours / 24);
hours%=24;
minutes%=60;
seconds%=60;
$('.time-elapsed').find('ul:eq(0)').find('li:eq(1)').html(days);
$('.time-elapsed').find('ul:eq(1)').find('li:eq(1)').html(hours);
$('.time-elapsed').find('ul:eq(2)').find('li:eq(1)').html(minutes);
$('.time-elapsed').find('ul:eq(3)').find('li:eq(1)').html(seconds);
var timeout = setTimeout('countdown()',1000);
}

不要使用字符串作为 setTimeout 的第一个参数。使用函数:

var timeout = setTimeout(countdown,1000);

我建议您使用setInterval(countdown,1000)并删除函数底部的setTimeout(countdown,1000)setInterval将无限重复countdown函数。

要阻止它,只需使用clearInterval(timeout);