与jQuery一起运行while循环而不会崩溃网站

时间:2015-05-23 16:01:03

标签: javascript jquery html

我需要一个不断运行的while循环来检查很多if (value < otherValue || value === otherValue)而不会使网站崩溃,仍然可以接受点击事件等... 以下是我的一些代码:

$(document).ready(function(){
    var value = 0;
    var otherValue = 25;
    var otherValue2 = 75;
    var otherValue3 = 100;
    var otherValue4 = 125;
    var otherValue5 = 175;
    var otherValue6 = 200;
    var otherValue7 = 300;
    $('#button').click(function(){
        value += 5;
        // Here i make the value show on the page like fancy, but It's not essential for this question
    });
});

那么,我如何包含一个不断运行的while循环,使该代码仍然有效,并且不会使网站崩溃?

1 个答案:

答案 0 :(得分:0)

我会看一下setInterval它会让你在每一段时间内执行一个函数。

&#13;
&#13;
var interval = null;
var value = 0;
var otherValue = 25;
var intervalTimer = 100; // 100ms

$('input').val(value);

$('button').on('click', function(){
    interval = setInterval(function(){
        $('input').val(value += 5);
    }, intervalTimer);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input>
    
<button>
    Start Updating Value 
</button>
&#13;
&#13;
&#13;