javascript - 如何让 JavaScript 倒数计时器在单击按钮时一次又一次地工作?
问题描述
单击ID 为 next-problem的按钮时,将向服务器发送AJAX请求并加载新任务。我想在加载新任务时重新启动计时器。在 AJAX 中,成功后我想重置计时器。但问题是许多setInterval在单击按钮时开始。如何避免这种情况?
var timer;
var countdownfunction;
var countDownTime;
timer = function (){
clearInterval(countdownfunction);
countDownTime = $("#timer").attr("data-timer-val");
var countdownfunction = setInterval(function() {
if(countDownTime < 10 ){
var temp = "0" + countDownTime;
$("#time").text(temp);
}else{
$("#time").text(countDownTime);
}
countDownTime = countDownTime - 1;
if (countDownTime < 0) {
clearInterval(countdownfunction);
$("#time-expired").text("Please click next problem.");
}
}, 1000);
} ;
$(document).ready(function(){
timer();
});
$(document).ready(function(){
$("#next-problem").on('click', function(){
$.ajax({
type : 'POST',
url : '/test/next-problem/',
success : function(data){
// console.log(data);
$("#problem-content").html(data);
clearInterval(countdownfunction);
timer();
},
});
});
});
解决方案
var
从以下行中删除:
var countdownfunction = setInterval(function() {
因此,var
您有两个不同范围的值,countdownfunction
所以当您调用时,clearInterval
您永远不会清除这个特定的功能范围值,直到该计时器达到-1
,因此您可能有多个计时器在彼此之上运行。
一旦你在这里删除var
,你现在有一个全局范围的变量,可以清除并重新分配一个值。
推荐阅读
- c# - 如何在单击快捷方式的显示器上显示我的 windows unity 应用程序?
- android - Android 无法获取我的 GPS 位置 - 一直等待 GPS
- reactjs - ag Grid 在单元格值更改时更改单元格颜色
- sql - 索引和 hasmap
- amazon-web-services - 使用同一区域中的 S3 存储桶的 AWS Cloudfront 源故障转移
- javascript - 从单独的组件重置条件渲染
- airflow - Cloud SQL 代理:负载下偶尔出现连接超时
- sql-server - 无法从 Google Cloud Compute Engine 连接到 Cloud SQL 服务器
- javascript - 录制开始时是否有保持闪光灯开启的解决方法?(iOS + Expo/Expo-camera)
- spring-batch - 是否可以使用不同的 sql 对象(字符串)在步骤之间共享阅读器?