这是我第一次在实际应用中使用while循环,请原谅我的无知。
我正在创建一个网页,展示随着时间的推移使用灯泡的成本。
在这个阶段,我正在尝试使用 while 循环来更新并显示自用户单击电灯开关以来经过的小时数。(1 小时代表 1 秒实时)
当我在萤火虫上设置断点时,一切都正常运行,直到我在我的 while 循环中到达 setTimeout 方法。在它在 setTimeout 方法处中断并单击继续后,它会立即再次在同一位置中断,而没有实际执行任何其他操作。
当我不设置断点时,它会冻结 firefox,我必须停止脚本执行。
我重新检查以确保我正确使用了 setTimeout。现在我什至不确定在哪里检查或搜索什么,因为我不明白出了什么问题。即使只是提示我可能会检查或研究的内容也会非常有帮助。
我试图尽可能详细地注释代码。如果需要,我很乐意澄清一些事情。
我强烈建议您看一下 jsfiddle:
但这是我的代码:
我的JS
$(document).ready(function () {
//set image to default off position
$('#lightswitch').css("background-image", "url(http://www.austinlowery.com/graphics/offswitch.png)");
// setup the lifetime hours of the lightbulb for later use
var lifetimeHours = 0;
// setup function to update the calculated lifetime hours number on the webpage to
// be called later
function updateLifetimeHoursHtml (lifetimeHours) {
$('#lifetimeHours').html(lifetimeHours);
}
// set up function to to send to setTimeout
function updateNumbers () {
// increment lifetimeHours by one
lifetimeHours = lifetimeHours++;
// call function to update the webpage with the new number result
updateLifetimeHoursHtml(lifetimeHours);
}
// When the lightswitch on the webpage is clicked, the user should see the
// lifetime hours update every second until the user clicks the switch again
// which will then display the off graphic and pause the updating of the lifetime
// hours
$('#lightswitch').click(function(){
// if the lightswitch is off:
if ($('#lightswitch').attr('state') == 'off') {
// set switch to on
$('#lightswitch').attr('state', 'on');
// update graphic to reflect state change
$('#lightswitch').css("background-image", "url(http://austinlowery.com/graphics/onswitch.png)");
// start updating the lifetime hours number on the webpage
// while the #lightswitch div is in the on state:
while ($('#lightswitch').attr('state') == 'on'){
//call update numbers every second
setTimeout('updateNumbers()', 1000);
}
// the lightswich was not in the off state so it must be on
}else{
// change the state of the switch to off
$('#lightswitch').attr('state', 'off');
// update graphic to reflect state change
$('#lightswitch').css("background-image", "url(http://austinlowery.com/graphics/offswitch.png)");
};
});
});
我的 HTML
<div id="container">
<div id="lightswitch" state="off"> </div>
<span>After </span><span id="lifetimehours">0</span><span> lifetime hours:</span>
<br><br>
<span><b>You have spent:</b></span>
<br><br>
<span id="dollaramoutelectricity"></span><span> on electricty</span>
<br>
<span id="mainttime"></span><span> on maintenace</span>
<br>
<span id="dollaramountbulbs"></span><span> on replacement bulbs</span>
<br><br>
<span><b>You have:</b></span>
<br><br>
<span>Produced </span><span id="amountgreenhousegasses"></span><span> of greenhouse gasses</span>
<br>
<span>Sent </span><span id="amounttrash"></span><span> of trash to the dump</span>
<br>
<span>Used </span><span id="amountelectricty"></span><span> of electricity</span>
</div>