延迟计时启动计时器

时间:2017-06-29 20:18:33

标签: javascript events timer setinterval stopwatch

在JavaScript中构建一个简单的倒计时器。 当我单击开始按钮时,单击按钮和计时器启动之间存在延迟。有人可以解释为什么会这样。我是JavaScript的初学者,所以我很清楚,很容易理解解释会非常感激。

提前谢谢



var startButton = document.getElementById("start");
var pauseButton = document.getElementById("pause");
var resetButton = document.getElementById("reset");
var minutesHTML = document.getElementById("minutes");
var secondsHTML = document.getElementById("seconds");
var seconds = 00;
var minutes = 00;
var myTimer = false;


startButton.onclick = startTimer;
pauseButton.onclick = pauseTimer;
resetButton.onclick = resetTimer;

function startTimer () {
	
	myTimer = setInterval (function () {
		
		if (seconds < 10) {
			secondsHTML.innerHTML = "0" + seconds;
		}
		if (seconds > 9) {
			secondsHTML.innerHTML = seconds;
		}
		
		
		seconds ++;
		
		if (seconds % 60 == 0) {
			minutes ++;
			seconds = 00;
		}
		
		if (minutes < 10) {
			minutesHTML.innerHTML = "0" + minutes;
		}
		
		if (minutes >= 10) {
			minutesHTML.innerHTML = minutes;
		}
		
	}		
	, 1000)
}


function pauseTimer () {
	clearInterval(myTimer);
}

function resetTimer () {
	seconds = 00;
	minutes = 00;
	secondsHTML.innerHTML = seconds;
	minutesHTML.innerHTML = minutes;
	
	console.log(secondsHTML + minutesHTML);
	clearInterval(myTimer);

}
&#13;
body{
	background: tomato;
	text-align: center;
	margin: auto;
	font-size: 50px;
}

h1 {
	font-size: 20px;
}

.button-container {
	display: flex;
	margin: auto;
}

button {
	text-align: center;
	border: none;
	width: 20%;
	background: #fff;
	font-size: 20px;
	margin: auto;
}
&#13;
<h1>TIMER</h1>


<p>
	<span id="minutes">00</span>
	:
	<span id="seconds">00</span>
</p>


<div class="button-container">
<button id="start"><p>START</p></button>
<button id = "pause"><p>PAUSE</p></button>
<button id = "reset"><p>RESET</p></button>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

setInterval在第一次运行函数之前等待一段时间(代码中的1000毫秒)。

您可以在致电setInterval之前自行致电该功能。这样你就可以得到一个立即呼叫,然后每秒一个呼叫,直到间隔被取消。

function tick () {

    if (seconds < 10) {
        secondsHTML.innerHTML = "0" + seconds;
    }
    if (seconds > 9) {
        secondsHTML.innerHTML = seconds;
    }


    seconds ++;

    if (seconds % 60 == 0) {
        minutes ++;
        seconds = 00;
    }

    if (minutes < 10) {
        minutesHTML.innerHTML = "0" + minutes;
    }

    if (minutes >= 10) {
        minutesHTML.innerHTML = minutes;
    }

}

function startTimer () {
    tick();   
    myTimer = setInterval(tick, 1000);
}