简体   繁体   English

使用clearInterval将jQuery计时器停止为0

[英]Stop jQuery timer at 0 using clearInterval

I'm having issues using clearInterval to stop my simple count timer once it is equal to 0. Essentially, timer goes past 0 into negative values instead of stopping at 0. I am creating a basic quiz that ideally will alert the user of the correct answers once the timer reaches and stops at 0. 我在使用clearInterval使其等于0时停止我的简单计数计时器时遇到问题。从本质上讲,计时器经过0变为负值,而不是从0停止。我正在创建一个基本测验,理想情况下会提醒用户正确的计数计时器到达并停止在0时回答。

Below is current code: 下面是当前代码:

 var count = 10; var gameTime; gameTime = setInterval("counter()", 1000); function convertSeconds(s){ var min = Math.floor(s / 60); var sec = s % 60; return min + ":" + sec; } function counter(){ count--; $("#timer").text(convertSeconds(count)); } if (count === 0) { clearInterval("#timer"); } else { //Do nothing } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Trivia</title> <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script> </head> <body> <div id ="timer">10</div> </body> 

Just move your if check into the counter function and clear the gameTime variable. 只需将if检查移入计数器功能并清除gameTime变量即可。

setInterval runs the provided function at the given interval so anything you want to run or check on that interval must happen in the provided function. setInterval以给定的时间间隔运行提供的函数,因此要在该间隔上运行或检查的任何事情都必须在提供的函数中发生。

 var count = 10; var gameTime; gameTime = setInterval("counter()", 1000); function convertSeconds(s){ var min = Math.floor(s / 60); var sec = s % 60; return min + ":" + sec; } function counter(){ count--; $("#timer").text(convertSeconds(count)); if (count === 0) { clearInterval(gameTime); } else { //Do nothing } } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Trivia</title> <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script> </head> <body> <div id ="timer">10</div> </body> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM