[英]Javascript setTimeout does not work.
有人可以解释为什么setTimeout()在这里不能正常工作吗? 函数timeLoop()仅运行一次。 我读了很多类似问题的答案,但都无济于事。
var Timer = function(){
var startTime;
var currentTime;
var stop = false;
var me = this;
this.initTimer = function(){
document.getElementById('timer').innerHTML = '0';
}
this.startTimer = function(){
this.start = new Date().getTime();
this.stop = false;
this.timeLoop();
}
this.stopTimer = function(){
this.stop = true;
}
this.timeLoop = function(){
if(this.stop) return;
this.currentTime = new Date().getTime() - this.start;
this.refreshTimer();
setTimeout(function(){me.timeLoop();}, 10);
}
this.refreshTimer = function(){
document.getElementById('timer').innerHTML = this.currentTime.toString();
}
}
该代码对我有用。 我怀疑您没有正确创建new Timer()
或未正确调用其方法。 以下作品:
<!DOCTYPE html>
<html>
<head>
<title>Some Title</title>
</head>
<body>
<div id='timer'>placeholder</div>
<button onclick="tim.startTimer();">Start</button>
<button onclick="tim.stopTimer();">Stop</button>
<script>
var Timer = function(){
var startTime;
var currentTime;
var stop = false;
var me = this;
this.initTimer = function(){
document.getElementById('timer').innerHTML = '0';
}
this.startTimer = function(){
this.start = new Date().getTime();
this.stop = false;
this.timeLoop();
}
this.stopTimer = function(){
this.stop = true;
}
this.timeLoop = function(){
if(this.stop) return;
this.currentTime = new Date().getTime() - this.start;
this.refreshTimer();
setTimeout(function(){me.timeLoop();}, 10);
}
this.refreshTimer = function(){
document.getElementById('timer').innerHTML = this.currentTime.toString();
}
}
var tim = new Timer();
</script>
</body>
</html>
您可能需要window.setInterval而不是setTimeout,请阅读此内容。 https://developer.mozilla.org/en-US/docs/Web/API/Window.setInterval
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.