Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在JS中重置setinterval_Javascript_Jquery_Setinterval - Fatal编程技术网

Javascript 在JS中重置setinterval

Javascript 在JS中重置setinterval,javascript,jquery,setinterval,Javascript,Jquery,Setinterval,代码如下所示: function startTimer(counter) { var interval = setInterval(function () { counter--; $('#timer').html(counter); // Display 'counter' wherever you want to display it. if (counter == 0) { clearInter

代码如下所示:

function startTimer(counter) {
    var interval = setInterval(function () {
        counter--;
        $('#timer').html(counter);
        // Display 'counter' wherever you want to display it.
        if (counter == 0) {
            clearInterval(interval);
            $('#question').html("Time ended");
            setTimeout(function () {
                window.location.href = "/";
            }, 5000);
            return false;
        }
    }, 1000);
}

我想做的是,当我多次调用此函数时,每次都将计时器重置为30秒,并杀死所有过去的实例。现在我打了很多次电话,都把过去的事情搞砸了。我做错了什么?

您必须在函数外定义var间隔:

   var interval;
    function startTimer(counter) {
        interval = setInterval(function () {
            counter--;
            $('#timer').html(counter);
            // Display 'counter' wherever you want to display it.
            if (counter == 0) {
                clearInterval(interval);
                $('#question').html("Time ended");
                setTimeout(function () {
                    window.location.href = "/";
                }, 5000);
                return false;
            }
        }, 1000);
    }
请参阅此链接: