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

607
Views
Why setInterval() is executed twice?

Why "hi" is being logged in the console each second twice?

import { useEffect } from "react";

export default function App() {
  useEffect(() => {
    setInterval(() => console.log("hi"), 1000);
  }, []);

  return (
    <div className="App">
      Hello
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

because that's what setInterval is all about.

From MDN:

The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

So you don't want to use setInterval because it will repeatedly execute your function, instead use setTimeout

about 4 years ago · Juan Pablo Isaza Report

0

In addition to what @AngryJohn wrote, you should also clear the interval when the component unmounts, by using clearInterval like so:


import { useEffect } from "react";

export default function App() {
  useEffect(() => {
    let interval = setInterval(() => console.log("hi"), 1000);

    return () => clearInterval(timer)  // This "return" function executes when a component unmounts
  }, []);

  return (
    <div className="App">
      Hello
    </div>
  );
}

Refer this SO question for more information.

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!