creating functionality for element to stop "setInterval" function (triggered by another element)

Viewed 61

I have created an automatic slideshow - which starts after clicking "menu item". I'm looking for a way to "turn it off", when clicking different "menu item". The whole problem can be abstracted to a simple example:

Constructing functionality for "stop" <li> (that would probably utilize stopInterval). I can't come up with a solution, would anyone have an idea ?

const li1 = document.getElementById("li1")

li1.addEventListener("click", slideShowAbstract)

function slideShowAbstract(e) {

    const y = setInterval(()=> console.log("playing"), 2000)

    }
ul {
    display: flex;
    justify-content: center;
    list-style-type: none;
  }
  
li {
    margin: 1rem;
}

li:hover {
    cursor: pointer;
}
            <ul>
                <li id="li1">play</li>
                <li id="li2">stop</li>
            </ul>

4 Answers

You can declare the y outside so that you can access it from multiple handlers.

const li1 = document.getElementById("li1")
const stopElement = document.getElementById("stopButton")
let intervalTimer;

li1.addEventListener("click", slideShowAbstract);
stopElement.addEventListener('click', stopSlideShow);


function slideShowAbstract(e) {
  intervalTimer = setInterval(() => console.log("playing"), 2000);
}

function stopSlideShow(){
  clearInterval(intervalTimer);
}

a better way ?

to avoid having global variables that can be jostled by side effects, use an object, to which you can add your useful methods.

const 
  btPlay = document.querySelector('#bt-play')
, player = (()=> // IIFE  for object { play(), stop() } method
  {
  let // inside Object values ( closure )
    refIntv   = 0
  , counter   = 0
  , onProcess = false // security to avoid multiple setInterval processes
    ;
  function playerAction()  // inside private function
    {
    console.clear()
    console.log( 'playing', ++counter)
    }
  return {
    play()
      {
      if (onProcess) return  // security to avoid doing setInterval() twice
      
      onProcess = true
      counter   = 0
      console.clear()
      console.log('start playing')
      refIntv = setInterval( playerAction , 2000)
      }
  , stop()
      {
      if (!onProcess) return  // security to avoid doing clearInterval() twice
 
      clearInterval( refIntv )
      onProcess = false
      
      console.clear()
      console.log('stop playing')
      }
    }
  })();


btPlay.onclick =_=>
  {
  if (btPlay.classList.toggle('stopped'))  player.play()
  else                                     player.stop()
  }
button { 
 margin : 1em 3em;
 width  : 5em; 
 }
#bt-play::after { 
 content : 'play';
 }
#bt-play.stopped::after { 
 content : 'stop';
 }
<h5> case 1: same button for start and stop </h5>

<button id="bt-play"></button>
<!-- control by interface : same button for start and stop -->
<hr>

<h5> case 2: 2 buttons   </h5>

<button onclick="player.play()">play</button>
<button onclick="player.stop()">stop</button>

interface control:
if you have 2 buttons (start + stop), the user can click 2 times on the start button and you you end up with 2 overlapping interval processes (or more) without the possibility of finding the reference of the previous setInterval since this variable has been replaced to reference the process of the following interval

if not you can also add a test verifying that there is no running interval process before.

Details commented in example

// Reference both items
const li1 = document.getElementById("li1");
const li2 = document.getElementById("li2");

// Bind both items to click event but call different handlers
li1.addEventListener("click", start);
li2.addEventListener("click", stop);

// Declare interval ID
let y;
// Define time interval
let t = 2000;
// Define counter
let tick = 0;
// Define the function to run on each interval
const log = () => console.log(t * tick++);

// Define the event handler called from li1
function start(e) {
  // If the tag clicked was #li1 and y isn't defined yet...
  if (e.target.matches('#li1') && !y) {
    // ...Initiate interval to call log()
    y = setInterval(log, t);
  }
}
// Define the event handler called from li2
function stop(e) {
  // If user clicked #li2...
  if (e.target.matches('#li2')) {
    // ...Stop interval...
    clearInterval(y);
    // ...reset interval ID
    y = null;
  }
}
ul {
  display: flex;
  justify-content: center;
  list-style-type: none;
}

li {
  margin: 1rem;
}

li:hover {
  cursor: pointer;
}
<ul>
  <li id="li1">play</li>
  <li id="li2">stop</li>
</ul>

const startBtn = document.getElementById("start")
const stopBtn = document.getElementById("stop")

const timer = {
    timerId : undefined,
    idx : 0,
    start(){
        if(timer.timerId)
           timer.stop();
      
        timer.timerId = setInterval(()=> {
                        document.getElementById("status").textContent = timer.idx++;
                        console.log(timer.idx);
                    }, 1000);
    },
    stop(){
        if(timer.timerId){
            clearInterval(timer.timerId);
            timer.idx = 0;
            timer.timerId = undefined;
            document.getElementById("status").textContent = timer.idx;
        }
    }
}

startBtn.addEventListener("click", timer.start);
stopBtn.addEventListener("click", timer.stop);
<button id="start">start</button>
<button id="stop">stop</button>
<br/>
<span id="status">

</span>

Related