一个倒计时器,在末端附近有闪烁的颜色

时间:2018-04-25 17:46:18

标签: javascript jquery

当我的计时器达到10秒以下时,我正试图为我的计时器创建一个闪烁效果。这就是我的计时器目前的样子:

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

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

        display.text(minutes + ":" + seconds);       			
        
    		if (--timer < 10) {
            setInterval(flash,1000);
        }
        
    }, 1000);    
}
function flash(){
        		$("#time").toggleClass("backgroundRed");
    }
jQuery(function ($) {
    var fiveMinutes = 20,
        display = $('#time');
    startTimer(fiveMinutes, display);
});
  .backgroundRed{
        background: red;
    }
<body>
    <div>Registration closes in <span id="time">00:20</span> minutes!</div>
</body>

目前闪光灯表现得非常古怪.... 提前致谢

1 个答案:

答案 0 :(得分:0)

作为一个非常简单的选择:

&#13;
&#13;
let flashInterval;

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

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

        display.text(minutes + ":" + seconds);       			
        
    	if (--timer < 10 && !flashInterval) {
            flashInterval = setInterval(flash,1000);
        }
        
    }, 1000);    
}

function flash(){
    $("#time").toggleClass("backgroundRed");
}
&#13;
&#13;
&#13;

通过修改条件以检查在设置新的闪存间隔之前是否已设置间隔,您可以确保仅设置一次。