简体   繁体   English

jQuery / JavaScript:使用相同的按钮启动和终止循环

[英]jQuery/JavaScript: Initiate and terminate a loop with the same button

I want to build a button that when I click it, the function in JavaScript associated with it initiates (so a loop inside it start doing something). 我想构建一个按钮,当我单击它时,与之关联的JavaScript函数会启动(因此,其中的循环开始执行某项操作)。

If I click it again before the loop inside the function finishes, the loop will terminates. 如果在函数内部的循环完成之前再次单击它,循环将终止。

If I click it again after the loop inside the function has already finished, the loop will just start as usual. 如果在函数内部的循环完成后再次单击它,则循环将照常开始。

How do I do this with the following code? 如何使用以下代码执行此操作? Thanks in advance. 提前致谢。

HTML: HTML:

<button id="startstop" class="btn btn-primary" onclick="count()">

JavaScript: JavaScript的:

function count() {
    var val = 0;
    var loop = setInterval(function(){
        val++;
        if (val > 1000} {
           clearInterval(loop);
        }
    }, 100);
}

try this code 试试这个代码

var loop; 
function count() {
    var val = 0;
      if (loop) {
        clearInterval(loop);
        loop = null;
      }
      else{
     loop = setInterval(function(){
        val++;
        console.log(val);
        if (val > 1000) {
           clearInterval(loop);
           loop = null;
        }
    }, 100);
      }
}

Place loop variable in global scope and everytime the user clicked stop previous loop if it's already started if not start it. loop变量放置在全局范围内,如果用户没有单击它,则每次单击时,如果它已经开始,则停止它。

Hope this helps. 希望这可以帮助。

 var loop=null; count = function () { var val = 0; //Stop previous loop if it's already started if(loop!=null){ clearInterval(loop); loop=null; }else{ loop = setInterval(function(){ val++; console.log(val); $('span').text(val); if (val >= 20) { clearInterval(loop); } }, 100); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="startstop" class="btn btn-primary" onclick="count()">Count</button> <span>0</span> 

I'm not a big fan of doing work for people, but on this occasion I'll succumb... 我不是为人做事的忠实粉丝,但是在这种情况下,我会屈从于...

You need to store the internal ID outside of the function, and base your process on that. 您需要将内部ID存储在函数外部,并以此为基础进行处理。 If the ID is not set, start the interval, if it is set stop the interval. 如果未设置ID,则开始间隔,如果已设置,则停止间隔。

Note, that I've massively reduced the length of interval, and the number of times it fires for this example... 请注意,在此示例中,我已大大减少了时间间隔的长度及其触发的次数...

 var _intervalId = -1; function count() { if (_intervalId == -1) { var val = 0; _intervalId = setInterval(function(){ val++; if (val > 200) { clearInterval(_intervalId); _intervalId = -1 document.getElementById("output").innerHTML = "stopped automatically"; } }, 10); document.getElementById("output").innerHTML = "started"; } else { clearInterval(_intervalId); _intervalId = -1; document.getElementById("output").innerHTML = "stopped manually"; } } 
 <button onclick="count();return false">Click Here</button> <div id="output"></div> 

I had fun building a small class for this. 为此我玩了一堂小课。 Feel free to use. 随时使用。

 // Counter class function Counter(callback, speed, max, init){ var loop = null; this.callback = callback; this.value = init || 0; this.max = max; function count(){ if (this.max && this.value >= this.max) { clearInterval(loop); loop = null; } else { this.value++; } this.callback(this.value); } this.start = function(){ if(!this.isStarted){ loop = setInterval(count.bind(this), speed); } }; this.stop = function(){ if(this.isStarted){ clearInterval(loop); loop = null; } } Object.defineProperty(this, "isStarted", { get: function(){ return !!loop; }}); } // Usage example. var result = document.getElementById("counter"); var button = document.getElementById("startstop"); // Create the counter and the callback. var counter = new Counter(function(val){ result.innerHTML = val; }, 100, 1000); // Init the result value. result.innerHTML = counter.value; // Listen for click events on the button. button.addEventListener("click", function(){ if(counter.isStarted){ counter.stop(); } else { counter.start(); } }); 
 <div id="counter"></div> <button id="startstop">Toggle</button> 

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

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