有没有办法让无限的while循环在后台运行?

时间:2020-07-19 15:00:10

标签: javascript while-loop infinite-loop

当用户单击按钮时,我希望函数无限发生直到用户再次按下该按钮。 我尝试创建类似于以下功能的函数,但陷入了无限循环,程序无法接受第二次用户单击,因此可以关闭该功能并重置所做的更改。

function doThing(){
    setBtnValue = "OFF"
    if( setBtnValue !== "ON"){
        setBtnValue = "ON"
        while (setBtnValue="ON"){
            //do this indefinitely
        }
    }
        //perform this on second button click
    if (setBtnValue !== "OFF"){
        setBtnValue = "OFF"
        // call function that will reset changes made to the element
    }
}

1 个答案:

答案 0 :(得分:0)

包装您的函数/代码,以检查while循环内是否有按钮单击。您还应该使用setTimeout()方法短暂地延迟循环,这样一秒钟之内就不会有100个循环,因为这可能导致浏览器冻结并导致调试器崩溃。