gpt4 book ai didi

Javascript setTimeout 不起作用。

转载 作者:行者123 更新时间:2023-12-03 12:29:34 24 4
gpt4 key购买 nike

有人可以解释一下为什么 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>

关于Javascript setTimeout 不起作用。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24004763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com