【问题标题】:Cannot seem to ClearInterval on this function? Clock counts down by 2, then 3, then 4似乎无法在此功能上使用 ClearInterval?时钟倒计时 2,然后 3,然后 4
【发布时间】:2011-07-11 09:52:11
【问题描述】:

我遇到了一个问题,我认为区间函数正在复合,这导致我的计数器倒计时 2,然后是 3,然后是 4,而它应该按 1 计数。

这是我的代码:

s = 0;
function deconInterval(passedObj, startTime) {


if(!seconds) {  
    seconds = (startTime*60 - 1);
    s = seconds;
}

minVar = Math.floor(s/60); 
secVar = s % 60;

if(secVar < 10) { 
    zeros = '0';
} else {
    zeros = '';
}

s--;
    passedObj.html(minVar +':'+zeros+ '' +secVar);
}

$('button').click(function() {


    if($(this).html() == 'Reload') {
        alert('Resetting Cards');
        window.location.reload()
    }

    $(this).html('Reload');


    intval = setInterval(displayTime, 60000);
    $(function(){
        $('li.item').map(function(){
            var _this = $(this);
            setTimeout(function(){
                $('.timeleft').remove();            
                $('li.item').removeClass('highlighted');
                _this.addClass('highlighted');

        timeval = _this.next().attr('data-time') - (_this.attr('data-time'))

        _this.prepend('<div class="timeleft">'+(timeval)+':00</div>');

        seconds = ""; //reset seconds
        timetabInterval = setInterval(function() { deconInterval(_this.children('.timeleft'), timeval); }, 1000);


            },(Number(_this.attr('data-time'))*60000));
        });
    });
});

【问题讨论】:

    标签: jquery settimeout jquery-events


    【解决方案1】:

    clearInterval 是您问题的答案。

    您不需要在点击处理程序中执行$(function(){...}),因为如果您设置了点击处理程序,则 dom 已准备就绪。

    【讨论】:

    • 谢谢,是的,我知道它是 clearInterval 但不执行 $(function(){}) 是个好建议
    【解决方案2】:

    我认为你不应该为 intval, timeval and timetabInterval 使用全局变量,否则你最终会将更多事件附加到同一个变量并搞砸一切(在你的情况下,我认为你将很多 setInterval 附加到 timetabInterval 和所以你最终向上计数 2,3 或 4)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 2021-05-01
      • 1970-01-01
      相关资源
      最近更新 更多