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

running a while loop alongside jQuery without crashing the website

本文关键字:网站 崩溃 一起 jQuery 运行 while 循环      更新时间:2023-09-26

我需要一个不断运行的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循环,使代码仍然有效,并且不会使网站崩溃?

我会看看setInterval,它将允许您每设置一段时间执行一个函数。

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);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input>
    
<button>
    Start Updating Value 
</button>