Skip to content

Instantly share code, notes, and snippets.

@odil-io
Created July 16, 2020 07:58
Show Gist options
  • Save odil-io/a1644ddba0b094afcc2e04550fcf61bd to your computer and use it in GitHub Desktop.
Save odil-io/a1644ddba0b094afcc2e04550fcf61bd to your computer and use it in GitHub Desktop.
JavaScript: count from Int to Int in X amount of time
// This function counts the integers/strings only containing numbers to the target integer
function animateValue(className, start, end, duration) {
// Get target element
var obj = document.getElementById(className);
// Set range
var range = end - start;
// Set minimum timer. Shorter than 50ms is not really visible any way
var minTimer = 50;
// Calculate step value
var stepTime = Math.abs(Math.floor(duration / range));
// Limit function to never go below minTimer
stepTime = Math.max(stepTime, minTimer);
// Get current dateTime
var startTime = new Date().getTime();
// Set end dateTime
var endTime = startTime + duration;
var timer;
// Run timing function on calculated interval
function run() {
var now = new Date().getTime();
var remaining = Math.max((endTime - now) / duration, 0);
var value = Math.round(end - (remaining * range));
obj.innerHTML = value;
if (value == end) {
clearInterval(timer);
}
}
timer = setInterval(run, stepTime);
run();
}
// ======== SINGLE ELEMENT EXAMPLE ======== //
// Example is set for 5 seconds.
animateValue('#element', 0, 1000, 5000);
// OR
// Get the element
var element = document.getElementById('#element');
// Get the target value
var element = element.getAttribute('data-target');
// Set duration (5 seconds)
var duration = 5000;
animateValue( element, 0, target, duration);
// ======== MULTIPLE ELEMENT EXAMPLE ======== //
// Example is set for 10 seconds.
// Get all target elements
var elements = document.querySelectorAll('.classname');
// For each element, assign animation
elements.forEach(element => {
// Get target value
var targetValue = element.getAttribute('data-target');
// Get element ID, important
var elementID = element.getAttribute('id');
// Run function
animateValue(elementID, 0, targetValue, 10000);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment