首页 > 解决方案 > 如何让 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();

            },

        });

    });

});

标签: javascriptjquery

解决方案


var从以下行中删除:

var countdownfunction = setInterval(function() {

因此,var您有两个不同范围的值,countdownfunction所以当您调用时,clearInterval您永远不会清除这个特定的功能范围值,直到该计时器达到-1,因此您可能有多个计时器在彼此之上运行。

一旦你在这里删除var,你现在有一个全局范围的变量,可以清除并重新分配一个值。


推荐阅读