3

每次我重置计时器时,计时器都会变得越来越快。我想我需要使用clearTimeout但不确定如何实现它。这是代码:

$(function(){
  sessionmin = 25;
  $("#sessionMinutes").html(sessionmin);
  $("#circle").click(function() {  
    timeInSeconds = sessionmin * 60;
    timeout();
  });
})

function timeout(){
  setTimeout(function () {
    if (timeInSeconds > 0) {
      timeInSeconds -= 1;
      hours = Math.floor(timeInSeconds/3600);
      minutes = Math.floor((timeInSeconds - hours*3600)/60);
      seconds = Math.floor(timeInSeconds - hours*3600 - minutes*60);
      $("#timer").html(hours + ":" + minutes + ":" + seconds);
    }
    timeout();
  }, 1000);
}
4

2 回答 2

1

您应该:使用setInterval而不是setTimeout,返回生成的间隔 id,setInterval在重新启动之前清除该间隔。这是一个例子:https ://jsfiddle.net/8n2b7x0s/

$(function(){
        var sessionmin = 25;
        var intervalId = null;
        $("#sessionMinutes").html(sessionmin);
        $("#circle").click(function() {  
            timeInSeconds = sessionmin * 60;
            // clear the current interval so your code isn't running multiple times
            clearInterval(intervalId);
            // restart the timer
            intervalId = run();
        });
 })

function run(){
    return setInterval(function () {
        if(timeInSeconds>0){
            timeInSeconds-=1;
            hours = Math.floor(timeInSeconds/3600);
            minutes = Math.floor((timeInSeconds - hours)/60);
            seconds = (timeInSeconds - hours*3600 - minutes*60)
            $("#timer").html(hours + ":" + minutes + ":" + seconds);
        }
    }, 1000);
}
于 2016-07-30T02:38:43.483 回答
1

您必须将您定义setTimeout为变量才能重置它。

见小提琴

var thisTimer;      // Variable declaration.
$(function(){
        sessionmin = 25;
        $("#sessionMinutes").html(sessionmin);
        $("#circle").click(function(){  
            clearTimeout(thisTimer);        // Clear previous timeout
            timeInSeconds = sessionmin * 60;
            timeout();
        });
 })

function timeout(){
    thisTimer = setTimeout(function () {    // define a timeout into a variable
        if(timeInSeconds>0){
        timeInSeconds-=1;
        hours = Math.floor(timeInSeconds/3600);
        minutes = Math.floor((timeInSeconds - hours)/60);
        seconds = (timeInSeconds - hours*3600 - minutes*60)
        $("#timer").html(hours + ":" + minutes + ":" + seconds);
        }
    timeout();
    }, 1000);
}
于 2016-07-30T02:39:15.203 回答