gpt-4.1-mini-2025-04-14· openai
from WildChat-4.8M
function updateCount(startNum, toNum, step, ms)
- User
function updateCount(startNum, toNum, step, ms)
- Assistant
Certainly! Here's a simple JavaScript function
updateCountthat counts fromstartNumtotoNumincrementing (or decrementing) bystepeverymsmilliseconds. The function prints the current count to the console at each step.javascriptfunction updateCount(startNum, toNum, step, ms) { let current = startNum; const increasing = startNum < toNum; const timer = setInterval(() => { console.log(current); if (increasing) { if (current >= toNum) { clearInterval(timer); } else { current += step; if (current > toNum) current = toNum; // Prevent overshoot } } else { if (current <= toNum) { clearInterval(timer); } else { current -= step; if (current < toNum) current = toNum; // Prevent overshoot } } }, ms); }Example usage:
javascriptupdateCount(0, 10, 2, 500); // Counts 0, 2, 4, 6, 8, 10 every 500 msIf you want to do something else with the current count (like updating the DOM), you can replace the
console.log(current);line with your custom code.Let me know if you need a version with callbacks or promises!