Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

129
Views
Javascript stop loop on hover?

I wanna make an element execute a function continuously while hovering my mouse and to stop executing it when I move my mouse away from it, but right now I can only start and no idea on how to make it stop

HTML:

<a onmouseover="randomizeHover(1)" id="link1" class="link" href="#">Home</a>

JS:

function randomize(id) {
  let element = document.getElementById("link" + id);
  element.innerHTML = "Ho" + makeid(2);
}

//generates random letters

function makeid(length) {
  var result = "";
  var characters = "abcdefghijklmnopqrstuvwxyz";
  var charactersLength = characters.length;
  for (var i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}

//makes it repeat itself

function randomizeHover(id) {
  console.log("Hello?");
  setInterval(() => {
    randomize(id);
  }, 200);
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Add a mouseleave event listener that clears the interval:

function randomize(id) {
  let element = document.getElementById("link" + id);
  element.innerHTML = "Ho" + makeid(2);
}

//generates random letters

function makeid(length) {
  var result = "";
  var characters = "abcdefghijklmnopqrstuvwxyz";
  var charactersLength = characters.length;
  for (var i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}

//makes it repeat itself

let interval;

function randomizeHover(id) {
  console.log("Hello?");
  interval = setInterval(() => {
    randomize(id);
  }, 200);
}
function stopRandomizer(){
  clearInterval(interval)
}
<a onmouseover="randomizeHover(1)" onmouseleave="stopRandomizer()" id="link1" class="link" href="#">Home</a>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!