我有一个HTML文件product.html
,它使用AJAX(通过按钮点击)插入到另一个HTML文件的div中。 product.html
中有一个计时器,如下所示:
product.html
:
<!-- HTML stuff -->
...
Bid time of the product: <div id="displayTime"></div>
...
<!-- HTML stuff -->
<div id="testChange">
<script>
$(document).ready(function() {
function updateTime() {
var newContent = $("#testChange").html();
if (newContent != oldContent) { // If the content of "testChange" changes, stop the timer
return;
}
timeStr = ... // prepare the time for display
$("#displayTime").html(timeStr);
setTimeout(updateTime, 1000);
}
function startUpdatingTime() {
oldContent = $("#testChange").html();
updateTime();
}
startUpdatingTime();
</script>
</div>
当我单击按钮时,文件product.html
被AJAX插入到另一个HTML的div中。计时器运行正常。但是,当我再次单击该按钮时,显然有两个计时器正在运行。如果我再次点击,将会有多个计时器正在运行。 displayTime
div正在闪烁,因为很多计时器正在尝试更新它。我的问题:我如何检查是否已经有一个计时器运行,这样就不需要运行一个新计时器。或者我该如何制止旧的呢?
答案 0 :(得分:1)
只需使用下面发布的clearTimeout
:
$(document).ready(function() {
var timeout, oldContent;
function updateTime() {
var newContent = $("#testChange").html();
if (newContent != oldContent) { // If the content of "testChange" changes, stop the timer
return;
}
timeStr = ... // prepare the time for display
$("#displayTime").html(timeStr);
if (timeout){
window.clearTimeout(timeout);
}
timeout = window.setTimeout(updateTime, 1000);
}
function startUpdatingTime() {
oldContent = $("#testChange").html();
updateTime();
}
startUpdatingTime();
});