如何将计时器停止在某个值

时间:2019-03-14 05:27:19

标签: javascript html

我已经创建了一个计时器,该计时器在您单击按钮时启动。我希望计时器在时间值达到5时停止,但由于某种原因它无法正常工作。

let words = document.getElementById("Words");
let wordAr = ["The" , "quick" , "brown" , "fox" , "jumped" , "over" , "the" , "lazy" , "dog"];
let textIn = document.getElementById("Input");
let timer = 0;
let time = document.getElementById("Timer");
let wPM = 0;
let wpm = document.getElementById("WPM");
let text = document.getElementById("text");

words.innerHTML = wordAr.slice(0,9).join(" ");

window.addEventListener("keydown", function(key){
	if(key.keyCode == 32){
		for (let i=0; i < 1; i++){
			wPM+=1;
			wpm.innerHTML = wPM;	
		};
	};
});

let start = document.getElementById("start");

function incTime(){
	timer++;
	time.innerHTML = timer;
};	

function initTime(){
	setInterval(incTime, 1000);
};

if(timer == 5){
	console.log("done");
};
我尝试添加.value并使用单等号和三等号,但所有尝试都是徒劳的。

3 个答案:

答案 0 :(得分:1)

booksb函数中添加计时器条件。并使用incTime()中断clearInterval()

setInterval

答案 1 :(得分:1)

您所遇到的问题是if(timer == 5)检查仅执行一次,而不会在每次 timer 值更新时进行检查。每次更新计时器时,您都需要检查该值。通过在 incTime()更新方法内移动支票

let words = document.getElementById("Words");
let wordAr = ["The" , "quick" , "brown" , "fox" , "jumped" , "over" , "the" , "lazy" , "dog"];
let textIn = document.getElementById("Input");
let timer = 0;
let time = document.getElementById("Timer");
let wPM = 0;
let wpm = document.getElementById("WPM");
let text = document.getElementById("text");

words.innerHTML = wordAr.slice(0,9).join(" ");

window.addEventListener("keydown", function(key){
    if(key.keyCode == 32){
        for (let i=0; i < 1; i++){
            wPM+=1;
            wpm.innerHTML = wPM;    
        };
    };
});

let start = document.getElementById("start");

function incTime(){
    timer++;
    time.innerHTML = timer;
    if(timer == 5){
        console.log("done");
    }
};  

function initTime(){
    setInterval(incTime, 1000);
};

答案 2 :(得分:-1)

您可以使用clearInterval()方法。

您的情况

let words = document.getElementById("Words");
let wordAr = ["The" , "quick" , "brown" , "fox" , "jumped" , "over" , "the" , "lazy" , "dog"];
let textIn = document.getElementById("Input");
let timer = 0;
let time = document.getElementById("Timer");
let wPM = 0;
let wpm = document.getElementById("WPM");
let text = document.getElementById("text");
let timerPid= null;

words.innerHTML = wordAr.slice(0,9).join(" ");

window.addEventListener("keydown", function(key){
    if(key.keyCode == 32){
        for (let i=0; i < 1; i++){
            wPM+=1;
            wpm.innerHTML = wPM;    
        };
    };
});

let start = document.getElementById("start");

function incTime(){
    timer++;
    time.innerHTML = timer;
};  

function initTime(){
    timerPid= setInterval(incTime, 1000);
};

if(timer == 5){
    clearInterval(timerPid);
};