簡體   English   中英

停止循環功能setTimeout

[英]Stop loop function setTimeout

我有一個使用setTimeout的循環,如下所示:

<button onclick="clickStop()">stop</button>

<script type="text/javascript">
    let i = 0;
    let sett;
    function timeOut(counter) {   
        sett = setTimeout(function () {
            $.get("./test3.php", {data_id: counter}, (data) => {
                console.log(data);
                i++;
                timeOut(i);
            });
        }, 1000);
        if(counter >= 10) {
            clearTimeout(sett);
            alert("Done!");
        }
    }
    timeOut(i);
    function clickStop() {
        clearTimeout(sett);
    }
</script>

但是當我點擊停止按鈕不起作用時,請幫助我!

您可以清除超時並設置一個標志,該標志將警告$.get中的回調,當它返回時,它不應調用timeOut()

 let i = 0; let sett; let active = true // should the loop continue? function timeOut(counter) { if (counter < 10){ sett = setTimeout(function () { $.get("./test3.php", {data_id: counter}, (data) => { console.log(data); i++; if (active) timeOut(i); // only if active }); }, 1000); } else { alert("Done!"); } } timeOut(i); function clickStop() { active = false // stop loop clearTimeout(sett); // and clear current timeout } 

您的JS似乎運行良好,請參見下文,當我單擊“停止”按鈕時,計數器會增加並停止。 問題是與$.get("./test3.php" ...

您能詳細說明一下ajax調用的預期響應是什么嗎?

另外,如果您可以描述您要做什么,我們可以為您提供一些最佳實踐的指導,因為正如評論的人所述,在循環中運行XHR / ajax調用通常不是一個好主意。

 <button onclick="clickStop()">stop</button> <script type="text/javascript"> let i = 0; let sett; function timeOut(counter) { sett = setTimeout(function () { timeOut(counter+1); console.log(counter); }, 1000); if(counter >= 10) { clearTimeout(sett); alert("Done!"); } } timeOut(i); function clickStop() { clearTimeout(sett); } </script> 

$.get響應處理程序中的timeout(i)會重新啟動循環,即使您已將其停止。 您可以使用標志來控制它。

 let i = 0; let sett; let status = true; let url = "http://placekitten.com/200/300"; function timeOut(counter) { sett = setTimeout(function () { $.get(url, (data) => { console.log(i); i++; // repeat if status flag is true if(status) timeOut(i); }); }, 1000); if(counter >= 10) { clearTimeout(sett); status = false; // set status flag to false alert("Done!"); } } function clickStop() { clearTimeout(sett); status = false; // set status flag to false } timeOut(i); 
 <button onclick="clickStop()">stop</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM