Skip to content

Commit

Permalink
Add progressive counter file
Browse files Browse the repository at this point in the history
  • Loading branch information
johnsi15 committed Jan 31, 2024
1 parent ddbff41 commit 055ae25
Show file tree
Hide file tree
Showing 4 changed files with 9 additions and 67 deletions.
1 change: 1 addition & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ module.exports = {
version: 'detect',
},
},
ignorePatterns: ['progressiveCounter.min.js'],
};
10 changes: 0 additions & 10 deletions example/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,6 @@ import './style.css';
import { ProgressiveCounter } from '../.';

const App = () => {
// const [isMounted, setIsMounted] = React.useState(false);

// React.useEffect(() => {
// setIsMounted(true);
// }, []);

// if (!isMounted) {
// return null;
// }

return (
<>
{/* prettier-ignore */}
Expand Down
7 changes: 7 additions & 0 deletions example/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@
text-align: center;
}

.counter {
font-size: 40px;
font-weight: bold;
color: rebeccapurple;
text-align: center;
}

body {
background-color: #000000;
display: grid;
Expand Down
58 changes: 1 addition & 57 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ interface Props {
delay?: number;
className?: string;
element?: string;
class?: string;
}

export function ProgressiveCounter({
Expand All @@ -31,60 +32,3 @@ export function ProgressiveCounter({

return React.createElement(element, { className }, count);
}

export function ProgressiveCounterJS() {
const progressiveCounter = ({
initialValue,
duration = 1500,
decimals = 0,
delay = 5,
finalValue,
}: Props) => {
let target = finalValue;
let current = initialValue;
let currentStep = 1;
let timeoutId: any;

const initial =
typeof initialValue === 'function' ? initialValue() : initialValue;

const lerp = (a: number, b: number, alpha: number) => {
return a + alpha * (b - a);
};

const easeOutCubic = (value: number) => {
return 1 - Math.pow(1 - value, 3);
};

const steps = Math.max(Math.floor(duration / delay), 1);

const setTimeoutHandler = () => {
const progress = currentStep / steps;
console.log({ progress, current });
if (progress === 1) {
current = target;
clearTimeout(timeoutId);
} else {
current = lerp(initial, target, easeOutCubic(progress));
currentStep = currentStep + 1;
timeoutId = setTimeout(setTimeoutHandler, delay);
}

console.log(current);

return current.toFixed(decimals);
};

timeoutId = setTimeout(setTimeoutHandler, delay);
};

console.log(
progressiveCounter({ initialValue: 1, finalValue: 200.98, decimals: 1 })
);

// document.querySelector('.counter')?.innerText = progressiveCounter({
// initialValue: 1,
// finalValue: 200.98,
// decimals: 1,
// });
}

0 comments on commit 055ae25

Please sign in to comment.