incognita
incognita

Reputation: 45

How to stop time out?

i am stuck When i open page after 2 sec i want to show random item for 1 sec. And than repeat it again. But when i hover item i want stop animation. how can i do it in a right way? at that moment i have this solution

let element = document.getElementsByClassName("triger");

const getRandomInt = (max) => Math.floor(Math.random() * Math.floor(max));
console.log(window.TIMERS)
const run = () => {
  let random = getRandomInt(3);
  element[random].classList.add("hover");
  setTimeout(() => {
    element[random].classList.remove("hover");
    return setTimeout(run, 2000);
  }, 1000);
};

const timeID = setTimeout(run, 2000);
console.log(timeID)
let a = document.getElementsByClassName("triger_wrap")[0];
a.addEventListener("mouseenter",  () => {
  console.log('a')
  clearTimeout(timeID)
});

will be glad any help

https://codepen.io/Timonck/pen/BaLKrBw

Upvotes: 0

Views: 76

Answers (1)

Luka Čelebić
Luka Čelebić

Reputation: 1093

At the bottom you're clearing timeID but the function itself already loops at the return setTimeout(run, 2000); line.

You need to clear the actual timeout inside the function. In the edit below it works as you wanted with the exception of requiring another line of code after the two clearTimeouts in order to remove the .hover class from the element which currently has it when we stop the timeout.

let element = document.getElementsByClassName("triger");
let timeout;

const getRandomInt = (max) => Math.floor(Math.random() * Math.floor(max));
const run = () => {
  let random = getRandomInt(3);
  element[random].classList.add("hover");
  timeout = setTimeout(() => {
    element[random].classList.remove("hover");
    return setTimeout(run, 2000);
  }, 1000);
};

const timeID = setTimeout(run, 2000);
let a = document.getElementsByClassName("triger_wrap")[0];
a.addEventListener("mouseenter",  () => {
  clearTimeout(timeID)
  clearTimeout(timeout);
  // find element with .hover class and remove it
});

Upvotes: 1

Related Questions