倒数计时器未通过clearInterval()停止

时间:2018-11-07 15:11:28

标签: javascript clearinterval

我在使此倒数计时器停止为零时遇到问题,因此该时间不会显示为负值。 console.log被调用并且可以正常工作,但是由于某种原因clearInterval()不能正常工作。这让我发疯,我快要辞职了。

const timerContainer = document.getElementById('timerContainer');   

const THREEMINUTES = 60 * 0.1;//5 seconds for testing
	
startTimer(THREEMINUTES, timerContainer);

function startTimer(duration, display) {

		let start = Date.now();
		let diff, min, sec;

		let timer = () => {
			diff = duration - (((Date.now() - start) /        1000) | 0);
			//use bitwise to truncate the float
			min = (diff / 60) | 0;
			sec = (diff % 60) | 0;

			min = min < 10 ? '0' + min : min;
			sec = sec < 10 ? '0' + sec : sec;

			display.textContent = min + ':' + sec;

			if (diff <= 0) {
				stopTimer();
				submit.disabled = 'true'; 
			};

		};

		//call timer immediately otherwise we wait a      full second
		timer();
		setInterval(timer, 1000);

		function stopTimer() {
			clearInterval(timer);
    	console.log("time's up", diff);
    };
}
<div id="timerContainer"></div>

3 个答案:

答案 0 :(得分:3)

您没有保存setInterval(timer, 1000);

的结果

您应该使用此:

let timerId;
timer();
timerId = setInterval(timer, 1000);

function stopTimer() {
    clearInterval(timerId);
    console.log("time's up", diff)
};

您可能会看到,setInterval的结果是一个数字(节点中的对象),然后您要做的就是将该值传递给clearInterval,因此我们将该值保存在变量中timerId供参考。

答案 1 :(得分:2)

不要将您要停止的功能传递给clearInterval()

传递对您启动的计时器的引用,,因此您需要确保在启动计时器时捕获对将要从其返回的ID的引用。

>
// Function that the timer will invoke
function callback(){
    . . .
}

// Set up and initiate a timer and capture a reference to its unique ID
var timerID  = setInterval(callback, 1000);

// When needed, cancel the timer by passing the reference to it
clearInterval(timerID);

答案 2 :(得分:0)

该代码是固定的,请确保您已修复提交按钮的代码。 您应该首先将setInterval的值分配给变量。该变量在调用clearInterval时使用,实际上会清除间隔。

const timerContainer = document.getElementById('timerContainer');   

const THREEMINUTES = 60 * 0.1;//5 seconds for testing

startTimer(THREEMINUTES, timerContainer);
var timer = null;
function startTimer(duration, display) {

        let start = Date.now();
        let diff, min, sec;

        let timer = () => {
            diff = duration - (((Date.now() - start) /        1000) | 0);
            //use bitwise to truncate the float
            min = (diff / 60) | 0;
            sec = (diff % 60) | 0;

            min = min < 10 ? '0' + min : min;
            sec = sec < 10 ? '0' + sec : sec;

            display.textContent = min + ':' + sec;

            if (diff <= 0) {
                stopTimer();
                submit.disabled = 'true'; 
            };

        };

        //call timer immediately otherwise we wait a      full second
        timer();
        timer = setInterval(timer, 1000);

        function stopTimer() {
            clearInterval(timer);
        console.log("time's up", diff);
    };
}