简体   繁体   English

Javascript / Toggle / Switch / clearInterval() - 当切换关闭时无法 clearInterval()

[英]Javascript / Toggle / Switch / clearInterval() - not able to clearInterval() when the toggle is switched off

wow, this is my first post, New to programming and coding.哇,这是我的第一篇文章,编程和编码新手。 this is something of my first projects I work on, I would like to be able to switch a toggle to run a code or to stop it.这是我从事的第一个项目,我希望能够切换开关来运行代码或停止它。 using the setInterval() for it.使用 setInterval() 。 But now I am not able to switch it off when selecting the toggle, Tried multiple thing;但是现在我在选择切换时无法将其关闭,尝试了多种操作; like break.像休息。 but not successful so far.但到目前为止还没有成功。 Would be great if any of you could point me in the right direction.如果你们中的任何人能指出我正确的方向,那就太好了。

Kind regards, Laurens亲切的问候,劳伦斯

Code in HTML HTML 中的代码

<card>
<p>Theft Script ON/OFF</p>
<label class="switch">
<input id="executeTheftScript" type="checkbox" > Toggle me
</label>
</card>

Code in Javascript Javascript 中的代码

function theftToggle(){
    var isChecked = document.getElementById("executeTheftScript").checked;
    if (isChecked) {
        var i = setInterval(function(){
            if (person1.credits === 0) {
                clearInterval(i);
                updateStats();
                console.log("You don't have any credits.");
            } else {
                theft();
                person1.credits--;
                updateStats();
            };
        }, 500);
    } else {
        console.log("Your script is stopped.");
    }
}

document.getElementById("executeTheftScript").addEventListener('click', theftToggle);

Running of the code;代码的运行;

在此处输入图像描述

you need addEventListener to the input and it better to set the setInterval variable outside function or make it global so it will not create duplicate setInterval.您需要将addEventListener添加到输入中,最好将 setInterval 变量设置在 function 之外或使其成为全局变量,这样它就不会创建重复的 setInterval。

 var interval; var person1 = { credits: 10 } // listen the input for checked change document.getElementById("executeTheftScript").addEventListener('change', theftToggle); function theftToggle() { var isChecked = document.getElementById("executeTheftScript").checked; if (isChecked) { interval = setInterval(function() { if (person1.credits === 0) { clearInterval(interval); updateStats(); console.log("You don't have any credits."); } else { theft(); person1.credits--; updateStats(); } }, 500); } else { clearInterval(interval) console.log("Your script is stopped."); } } function theft() {} function updateStats() { console.log("credits: ", person1.credits); }
 <card> <p>Theft Script ON/OFF</p> <label class="switch"> <input id="executeTheftScript" type="checkbox"> Toggle me </label> </card>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM