【发布时间】:2013-01-03 20:52:55
【问题描述】:
我想在 Javascript 中创建一个简单的计时器,它从给定时间倒计时直到它达到 0。我发现这个 tutorial 工作得很好。我的问题是我需要在同一页面上放置多个计时器。本教程显然不会这样做,因为它使用全局变量(我是 JS/Programming 的新手,所以我可能没有使用正确的术语)。我试图重新创建相同的东西,只创建每个计时器作为它自己的对象,这样它们就不会相互干扰。这就是我所拥有的。
function taskTimer(name, startTime) {
this.timer = name;
this.totalSeconds = startTime;
this.tick = function() {
if (this.totalSeconds <= 0) {
return;
}
this.totalSeconds -= 1;
this.updateTimer();
// window.setTimeout("this.tick()", 1000);
};
this.updateTimer = function(){
this.seconds = this.totalSeconds;
this.hours = Math.floor(this.seconds / 3600);
this.seconds -= this.hours * (3600);
this.minutes = Math.floor(this.seconds / 60);
this.seconds -= this.minutes * (60);
this.timeString = this.leadingZero(this.hours) + ":" + this.leadingZero(this.minutes) + ":" + this.leadingZero(this.seconds);
return this.timeString;
};
this.leadingZero = function(time){
return (time < 10) ? "0" + time : + time;
};
}
var testTimer = new taskTimer("timer", 30);
testTimer.tick();
我最后在那里创建了一个。跑步
testTimer.updateTimer(); 返回 00:00:30 这是正确的,但运行 testTimer.tick(); 不会返回任何值。这部分代码显然有问题,我就是想不通。
【问题讨论】:
-
如何判断这是否有效?您没有在任何地方绘制任何计时器值。
-
因为updateTimer方法有效,所以调用tick方法应该返回相同的值,因为它调用了它内部的updateTimer方法。
-
"
testTimer.tick();没有返回值" 这是您要解决的问题吗?如果是这样,该函数永远不会返回任何内容。你需要一个return声明。 -
但是 testTimer.tick();调用 updateTimer();确实返回值的方法。这不应该意味着 testTimer.tick();会返回相同的值吗?
-
@SMDeConto updateTimer 返回一个值来打勾,但打勾不会把它返回给你。
标签: javascript object counter