How can I stop the interval using the same button I used to start the interval?

function slideShow() {
   'use strict';
    var pics = ['IMG_2135.jpg', 'IMG_2125.jpg', 'IMG_2119.jpg', 'IMG_2118.jpg'];
    var output = document.getElementById('output');
    output = pics[Math.floor(Math.random() * pics.length)];
    document.getElementById('image').src = output;
} 
button.onclick = function () { setInterval(slideShow, 2000); }
有帮助吗?

解决方案

var interval;    
button.onclick = function () { 
   interval = setInterval(slideShow, 2000); // assigned to a variable
}

You definitely need a variable to be assigned to the setInterval, which can be stopped using

clearInterval(interval);

How can I stop the interval using the same button I used to start the interval?

You do this by setting up a boolean check flag like

var isRecursiveOn = true;  // by default it will be true
var interval;
    button.onclick = function () {            
       if  (isRecursionOn) {  // check the flag
            isRecursiveOn = false;
            interval = setInterval(slideShow, 2000); // assigned to a variable                
       } else {
           clearInterval(interval);
           isRecursiveOn = true; //reset it
       }       
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top