setTimeout导致无限循环

时间:2012-08-29 21:54:17

标签: javascript jquery while-loop infinite-loop

这是我第一次在实际应用中使用while循环,所以请原谅我的无知。

我正在创建一个网页,演示了随着时间的推移使用灯泡的成本。

在这个阶段,我尝试使用while循环来更新并显示自用户点击灯光开关后经过的小时数。 (1小时代表实时1秒)

当我在firebug上设置断点时,一切都正常运行,直到我在while循环中进入setTimeout方法。在setTimeout方法中断后,我点击继续,它会立即再次在同一个地方中断,而不会实际执行任何其他操作。

当我没有设置断点时,它会冻结firefox并且我必须停止脚本执行。

我重新检查以确保我正确使用setTimeout。现在我甚至不确定在哪里检查或搜索什么因为我不明白哪里出错了。即使只是暗示我可能检查或研究的内容也会非常有用。

我试图尽可能详细地评论代码。如果需要,我会很乐意澄清一些事情。

我强烈建议你看一下jsfiddle:

JS FIDDLE

但这是我的代码:

我的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">&nbsp;</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>

4 个答案:

答案 0 :(得分:3)

var switchTimer;

$('#lightswitch').click(function(){
    if ($('#lightswitch').attr('state') == 'off') {
        $('#lightswitch').attr('state', 'on');
        switchTimer = setInterval(updateNumbers, 1000);
    } else {
        $('#lightswitch').attr('state', 'off');
        $('#lightswitch').css("background-image", "url(http://austinlowery.com/graphics/offswitch.png)");
        clearInterval(switchTimer);
    };

Javascript是一种基于事件的语言。这意味着代码不会持续运行。它只在有事件时运行。通过使用while循环,你基本上已经冻结了它 - javascript在该循环中不断运行。这对于像C这样的语言来说很好,它们必须一直运行。

但这对javascript来说是一个错误。对于javascript,您必须对其进行编码以响应事件,然后停止。 setInterval会不断为您生成一个事件,每隔xx毫秒运行一次函数。

在计时器的两次运行之间没有代码正在运行!这一点很重要。

答案 1 :(得分:3)

JavaScript使用事件循环。因为while循环永远不会产生(#lightswitch'state永远是on,因为无限循环会锁定用户界面,阻止用户将其关闭),事件循环永远不会再次运行,并且您在setTimeout注册的回调永远不会有机会执行。

您真正想做的是使用setInterval功能更新您的计数器。

setInterval(updateNumbers, 1000);

答案 2 :(得分:1)

根据yngum的回答,

我认为这样更好:

if ($('#lightswitch').attr('state') == 'off') {
    $('#lightswitch').attr('state', 'on');
    $('#lightswitch').css("background-image", "url(http://austinlowery.com/graphics/onswitch.png)");
    updateNumbers();
}

然后

function updateNumbers () {
    lifetimeHours++;
    updateLifetimeHoursHtml(lifetimeHours);
    if($('#lightswitch').attr('state') == 'on'){
        setTimeout(updateNumbers,1000);
    }
}

请在此处查看:http://jsfiddle.net/tdS3A/24/

但是如果你想要最高精度,你应该存储new Date().getTime(),因为执行{1}}或{1}} 1秒并不能确保你每秒都会调用它...

setTimeout

请在此处查看:http://jsfiddle.net/tdS3A/26/

即使您希望数字具有最大精度,因为您希望计算精确,也许您希望在向用户显示该值时将其舍入。然后,使用

setInterval

答案 3 :(得分:0)

由于setTimeout通常比setInterval更受欢迎,因此另一个解决方案是

更改

while ($('#lightswitch').attr('state') == 'on'){
    //call update numbers every second
    setTimeout('updateNumbers()', 1000);

setTimeout(function() {  
    updateNumbers();
    if ($('#lightswitch').attr('state') == 'on') 
        setTimeout(arguments.callee, 1000);
    }, 0);

这将每秒检查你的灯光开关,并在它关闭时停止。