JavaScript create a counter with the specified range, step and duration for the specified selector

const counter = (selector, start, end, step = 1, duration = 2000) => { let current = start, _step = (end - start) * step < 0 ? -step : step, timer = setInterval(() => { current += _step; document.querySelector(selector).innerHTML = current; if (current >= end) document.querySelector(selector).innerHTML = end; if (current >= end) clearInterval(timer); }, Math.abs(Math.floor(duration / (end - start)))); return timer; };
Code language: JavaScript (javascript)

Demo using JavaScript create a counter with the specified range, step and duration for the specified selector

counter(‘#const7-com-counter’, 0, 1000, 1, 10000);

0

Leave a Reply