user8006446
user8006446

Reputation: 475

Simple countdown - onClick button fires on render

I'm trying to build a very simple 5 second countdown in React and can't seem to get it to work. In the code below, the timer starts as soon as the app renders for the first time, and then once it gets past 0 it seems to flicker and break down.

Any suggestions?

import './styles/App.css';
import { useState } from 'react';

function App() {
    
  const [ time, setTime ] = useState(5);

  const startCountdown = setInterval(() => {
      if (time < 0 ) {
        clearInterval(startCountdown);
      }
      setTime(time - 1);
  }, 1000);
  
  return (
    <div className="App">
      <h1>{time}</h1>
      <button onClick={startCountdown}>Start</button>
    </div>
  );
}

export default App;

Upvotes: 1

Views: 246

Answers (1)

Arun Kumar M S
Arun Kumar M S

Reputation: 183

You need to pass it as a function. Currently your assigning this as code block which will be executed straightway. exp:

const startCountdown = () => setInterval(() => {
      if (time < 0 ) {
        clearInterval(startCountdown);
      }
      setTime(time - 1);
  }, 1000);

Upvotes: 1

Related Questions