Javascript:如何使用setInterval重置此倒计时器?

时间:2016-09-15 09:04:12

标签: javascript jquery

我有这个倒计时器,它使用setInterval

var startTimer = function(duration, display) {
    var timer = duration, minutes, seconds;

    var intervalHandler = setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        var timer_li = document.createElement("li");
        timer_li.id = "timer-li";
        timer_li.className = "navbar-text enabled";
        timer_li.title = "Autorefresh is enabled";
        timer_li.style.cursor = "pointer";
        timer_li.style.marginTop = "5px";

        if (timer_is_enabled) {
            console.log("Autorefreshing in: " + minutes + ":" + seconds);
            timer_li.innerHTML = "<i class='fa fa-refresh enabled'></i>";
            timer_li.title = "Autorefreshing in: " + minutes + ":" + seconds;
        } else {
            console.log("Autorefreshing disabled");
            timer_li.innerHTML = "<i class='fa fa-refresh changelog-icon'></i>";
            timer_li.title = "Autorefreshing is disabled";
        }

        if (minutes == "00" && seconds == "00" && timer_is_enabled) {
            manageTimer();
        }

        // button to enable/disable the timer
        timer_li.addEventListener("click", function(){
            timer_is_enabled = !timer_is_enabled;
        });

        if(document.getElementById("timer-li")) {
            document.getElementById("timer-li").remove();
        }

        var navbar = $("#user");
        navbar.after(timer_li);

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
};

我需要能够重置某些事件,例如点击某种类型的链接时:

$(".main-tab").click(resetTimer);

我知道我应该使用clearInterval,但我每次都会在代码中混乱。

点击按钮时如何重置此计时器的任何帮助?

1 个答案:

答案 0 :(得分:0)

试试这个:

-(void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:YES];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav-back"]
                                                                         style:UIBarButtonItemStylePlain
                                                                        target:self
                                                                        action:@selector(leftItemTapped:)];

}

在点击处理程序中,使用var intervalHandler; // global var var startTimer = function(duration, display) { var timer = duration, minutes, seconds; intervalHandler = setInterval(function () { ... };