Skip to content

Instantly share code, notes, and snippets.

@abelsan
Created August 15, 2020 23:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abelsan/6fb8a501daa4e55a0a98dea5bea4ff65 to your computer and use it in GitHub Desktop.
Save abelsan/6fb8a501daa4e55a0a98dea5bea4ff65 to your computer and use it in GitHub Desktop.
synchronizing 3 children counters
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Clock</title>
<!-- don't use this in production: -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<h1 style="font-family: Arial;">counters</h1>
<!-- target div -->
<div id="root"></div>
<!-- load react -->
<script
src="https://unpkg.com/react/umd/react.development.js"
crossorigin
></script>
<script
src="https://unpkg.com/react-dom/umd/react-dom.development.js"
crossorigin
></script>
<!-- react component. -->
<script src="many.js" defer type="text/babel"></script>
</body>
</html>
const Counter = (props) => {
const [counter, setCounter] = React.useState(Number(props.start));
// useRef to avoid the closure in the timer
const countRef = React.useRef(counter);
countRef.current = counter;
// timer
React.useEffect(() => {
const timeout = setTimeout(() => {
setCounter(counter + Number(props.increment));
props.parent({counter: countRef.current, label: props.label});
console.log(`child-${props.label}: ${countRef.current}`);
}, props.interval);
// cleanup
return () => {
clearTimeout(timeout);
}
}, [counter]);
return (
<>
Child-{props.label}: {counter}
</>
);
}
const Stats = () =>{
const [stats01, updateStats01] = React.useState(0);
const [stats02, updateStats02] = React.useState(0);
const [stats03, updateStats03] = React.useState(0);
function parent(msg){
switch(msg.label) {
case 'one':
updateStats01(msg.counter);
console.log('parent-one: ' + msg.counter);
break;
case 'two':
updateStats02(msg.counter);
console.log('parent-two: ' + msg.counter);
break;
case 'three':
updateStats03(msg.counter);
console.log('parent-three: ' + msg.counter);
break;
default:
console.log('Error: no matching case!');
}
}
return (
<div>
Parent-one: {stats01},
<Counter
label="one"
start="0"
increment="2"
interval="2000"
parent={parent} /><br/>
Parent-two: {stats02},
<Counter
label="two"
start="0"
increment="10"
interval="4000"
parent={parent} /><br/>
Parent-three: {stats03},
<Counter
label="three"
start="0"
increment="5"
interval="1000"
parent={parent} /><br/>
</div>
)
}
ReactDOM.render(
<Stats />,
document.getElementById('root')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment