Created
December 1, 2020 15:05
-
-
Save cziem/f2fdfc7cbed6675c7dc3609acda44f10 to your computer and use it in GitHub Desktop.
Print message to the screen every 1 second
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
const PrintMessage = () => { | |
const fontFamilies = ["arial", "cursive", "monospace", "sans-serif", "sans"]; | |
let [count, setCount] = React.useState(0); | |
const printMessage = () => { | |
return <span className={`${fontFamilies[count]} world`}>World</span>; | |
}; | |
useInterval(() => { | |
// Your custom logic here | |
if (count < fontFamilies.length - 1) { | |
setCount(count + 1); | |
} else { | |
setCount(0); | |
} | |
}, 1000); | |
function useInterval(callback, delay) { | |
const savedCallback = React.useRef(); | |
// Remember the latest function. | |
React.useEffect(() => { | |
savedCallback.current = callback; | |
}, [callback]); | |
// Set up the interval. | |
React.useEffect(() => { | |
function tick() { | |
savedCallback.current(); | |
} | |
if (delay !== null) { | |
let id = setInterval(tick, delay); | |
return () => clearInterval(id); | |
} | |
}, [delay]); | |
} | |
return ( | |
<div> | |
<h3>Hello {printMessage()}</h3> | |
</div> | |
); | |
}; | |
export default PrintMessage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment