1setInterval(function(){
2 console.log("Oooo Yeaaa!");
3}, 2000);//run this thang every 2 seconds
1import React, { useState, useEffect } from 'react';
2
3const IntervalExample = () => {
4 const [seconds, setSeconds] = useState(0);
5
6 useEffect(() => {
7 const interval = setInterval(() => {
8 setSeconds(seconds => seconds + 1);
9 }, 1000);
10 return () => clearInterval(interval);
11 }, []);
12
13 return (
14 <div className="App">
15 <header className="App-header">
16 {seconds} seconds have elapsed since mounting.
17 </header>
18 </div>
19 );
20};
21
22export default IntervalExample;
23
24
25//__________________________________________//
26function Counter() {
27 let [count, setCount] = useState(0);
28 let [delay, setDelay] = useState(1000);
29
30 useInterval(() => {
31 // Your custom logic here
32 setCount(count + 1);
33 }, delay);
34
35 function handleDelayChange(e) {
36 setDelay(Number(e.target.value));
37 }
38
39 return (
40 <>
41 <h1>{count}</h1>
42 <input value={delay} onChange={handleDelayChange} />
43 </>
44 );
45}
1useEffect(() => {
2 const interval = setInterval(() => {
3 console.log('This will run every second!');
4 }, 1000);
5 return () => clearInterval(interval);
6}, []);
1setInterval(function(){
2 console.log("print this once every 3 second");
3}, 3000);//run this thang every 3 seconds
1let myCounter = 0;
2let timeout = null;
3export default CounterApp = props => {
4
5 const [counter, setCounter] = useState(0);
6
7 // Also don't forget this
8 useEffect(()=> {
9 return ()=> clearInterval(timeout);
10 }, []);
11
12 myCounter = counter;
13 const startInterval = () => {
14 timeout = setInterval(() => {
15 setCounter(counter => counter + 1);
16 console.log("counter: ", myCounter); // counter always return 0 but myCounter the updated value
17 if(myCounter === 10) clearInterval(timeout);
18
19 }, 1000);
20 };
21
22}
23
1timer: function() {
2 var newCount = this.state.currentCount - 1;
3 if(newCount >= 0) {
4 this.setState({ currentCount: newCount });
5 } else {
6 clearInterval(this.state.intervalId);
7 }
8},
9