简体   繁体   English

简单计时器-为什么使用setTimeout()的函数内部的函数调用失败?

[英]simple timer- why does a function call inside a function using setTimeout() fail?

I am learning some JavaScript and experimenting with a simple countdown timer. 我正在学习一些JavaScript,并尝试了一个简单的倒数计时器。 The countdown fails if I insert checkTime() in the timedCount() function. 如果我在timedCount()函数中插入checkTime(),则倒数计时将失败。 I want the script to display a message in the 'warning' div, when the seconds remaining (var c) is a given integer (in this case 100 sec). 当剩余秒数(var c)是给定的整数(在这种情况下为100秒)时,我希望脚本在“警告” div中显示一条消息。 When I insert the checkTime() function the script displays 100 and stops. 当我插入checkTime()函数时,脚本显示100并停止。 It does the same when I put the function inside timeCount() function. 当我将函数放在timeCount()函数中时,它的作用相同。 I'm stumped! 我很沮丧!

 var c = 120; var t; var timer_is_on = 0; start.onclick = startCount; reset.onclick = resetCount; function timedCount() { document.getElementById("clock").innerHTML = c; c = c - 1; checkTime(); t = setTimeout(function() { timedCount() }, 1000); } function startCount() { if (!timer_is_on) { timer_is_on = 1; timedCount(); document.getElementById('start').style.display = 'none'; document.getElementById('reset').style.display = 'none'; document.getElementById('stop').style.display = 'block'; } } function stopCount() { clearTimeout(t); timer_is_on = 0; document.getElementById('start').style.display = 'block'; document.getElementById("start").innerHTML = "Resume"; document.getElementById('reset').style.display = 'block'; document.getElementById('stop').style.display = 'none'; } function resetCount() { clearTimeout(t); c = 0; timer_is_on = 0; document.getElementById("txt").value = 0; document.getElementById('start').style.display = 'block'; document.getElementById("start").innerHTML = "Start!"; } function checkTime() { if (c = 100) { document.getElementById("warning").innerHTML = "Time nearly up!"; } } 
 <div style="font-size:30px;"><span id="clock">0</span> <span>:seconds</span></div> <div id="warning"></div> <button id="start">Start count!</button> <button id="stop" onclick="stopCount()">Pause!</button> <button id="reset">Reset!</button> 

(c = 100)应该是(c === 100),您打算在要检查是否相等时设置。

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

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