Skip to content

Instantly share code, notes, and snippets.

@nastyakitsune
Created July 26, 2019 17:18
Show Gist options
  • Select an option

  • Save nastyakitsune/965a50892debf48b5f7d9fe532ded6cb to your computer and use it in GitHub Desktop.

Select an option

Save nastyakitsune/965a50892debf48b5f7d9fe532ded6cb to your computer and use it in GitHub Desktop.
Simple countdown timer with React Hooks
import React, { useState, useEffect } from "react";
import "./index.css";
// const date = { dateNum: 199, dateType: 'min', dateInterval: 60000 } - prop for CountdownTimer
const CountdownTimer = ({ dateNum, dateType, dateInterval }) => {
const [num, setNum] = useState(dateNum);
useEffect(() => {
const interval = setInterval(() => {
if (num > 0) {
setNum(num => num - 1);
}
}, dateInterval);
return () => clearInterval(interval);
}, [num, dateInterval]);
const dateTypeFormatted = num === 1 ? `${dateType}` : `${dateType}s`;
return (
<div className="timerContainer">
<span className="timerCount">{num}</span>
<br />
<span className="timerDateType">{dateTypeFormatted}</span>
</div>
);
};
@ManiaciaChao
Copy link

In fact, setInterval here is actually doing the same thing as setTimeout.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment