set interval react code example
Example 1: javascript setinterval
setInterval(function(){
console.log("Oooo Yeaaa!");
}, 2000);
Example 2: setinterval react
import React, { useState, useEffect } from 'react';
const IntervalExample = () => {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds => seconds + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
return (
<div className="App">
<header className="App-header">
{seconds} seconds have elapsed since mounting.
</header>
</div>
);
};
export default IntervalExample;
function Counter() {
let [count, setCount] = useState(0);
let [delay, setDelay] = useState(1000);
useInterval(() => {
setCount(count + 1);
}, delay);
function handleDelayChange(e) {
setDelay(Number(e.target.value));
}
return (
<>
<h1>{count}</h1>
<input value={delay} onChange={handleDelayChange} />
</>
);
}
Example 3: javascript setinterval
setInterval(function(){
console.log("print this once every 3 second");
}, 3000);
Example 4: setinterval react
let myCounter = 0;
let timeout = null;
export default CounterApp = props => {
const [counter, setCounter] = useState(0);
useEffect(()=> {
return ()=> clearInterval(timeout);
}, []);
myCounter = counter;
const startInterval = () => {
timeout = setInterval(() => {
setCounter(counter => counter + 1);
console.log("counter: ", myCounter);
if(myCounter === 10) clearInterval(timeout);
}, 1000);
};
}