【发布时间】:2017-05-30 22:29:11
【问题描述】:
我最近正在制作一个计时器对象和一个计时函数,它会根据 setTimeout 循环每秒计时一次。但是,滴答作响并没有延迟。如果你尝试下面的代码,你会发现时间数在几秒钟内就增加到了数千。如果有的话,我做错了什么?
<html>
<head>
</head>
<button onclick="startTimer()">Start</button>
<button onclick="stopTimer()">Stop Timer</button>
<button onclick="readTimer()">Read Timer</button>
<script>
function tick(){
console.log("TICK TOCK");
if(this.running == true){
this.time += 1;
console.log("HELLO!");
setTimeout(this.tick(), 1000, $(this));
}
}
function start(){
this.running = true;
this.tick();
}
function read(){
return this.time;
}
function stop(){
this.running = false;
}
function reset(){
if(this.running == false){
this.time = 0;
}else {
this.time = 0;
}
this.tick();
}
function timer(){
this.running = false;
this.time = 0;
this.start = start;
this.read = read;
this.stop = stop;
this.reset = reset;
this.tick = tick;
}
var t = new timer();
function startTimer(){
t.start();
}
function stopTimer(){
t.stop();
}
function readTimer(){
alert("This is the current Timer Reading: " + t.time);
}
</script>
</html>
【问题讨论】:
-
您将一个已执行的函数而不是一个函数传递给
setTimeout。做setTimeout(this.tick.bind(this), 1000). -
有效!非常感谢。如果没有你的帮助,我不会解决这个问题。
标签: javascript settimeout