patternjavascriptMinor
Showing animated company KPI stats
Viewed 0 times
showingcompanyanimatedstatskpi
Problem
I am creating a web page in which I have 4 different numbers which show companies stats. I am using javascript to dynamically show these numbers from 0 to n (where 0 is the starting point of counter and n is the end, I have n=74, n=86, n=285, n =97). I am using javascript to start the counter from 0 to n, everything is working fine, as I am just a beginner in programming so I just want to know how experienced programmers think of this code. is this a good approach for this problem? Can the algorithm efficiency be improved?
position: absolute;
top: 30px;
left: auto;
right: 30px;
border: none;
background-color: black;
color: white;
padding: 10px;
cursor: pointer;
}
button:hover {
background-color: crimson;
}
0
Styles Created
0
Awards Won
0
Stores Worldwide
0
Varities Desinged
START`
//I am invoking this function on scroll but here I have provided the button
function letsCount(){
var num = document.getElementsByClassName('number');
var count = 0;
var id = setInterval(myFunction,1);
var val = document.getElementById('value');
function myFunction(){
if(count == 286 ){ //stop the counter at this value
clearInterval(id);
}
else if(count
button {position: absolute;
top: 30px;
left: auto;
right: 30px;
border: none;
background-color: black;
color: white;
padding: 10px;
cursor: pointer;
}
button:hover {
background-color: crimson;
}
0
Styles Created
0
Awards Won
0
Stores Worldwide
0
Varities Desinged
START`
Solution
Keep the global scope clean and data/code segregation
First I will say your code is good for a beginner but you are missing some concepts and techniques that will help you improve your code and improve the client experience.
Some important concepts
The javascript
Always start your code with "use strict" it helps you avoid some very common bugs and bad coding styles and runs your code significantly faster.
try to define your event handlers as named functions because you need a function referance to remove the event if you need to.
We only want this to play once. So remove the event from the button. When events are called this
First I will say your code is good for a beginner but you are missing some concepts and techniques that will help you improve your code and improve the client experience.
Some important concepts
- Use requestAnimationFrame for animations, and know the difference between animation and one off content changes.
- Data belongs in the page. Be it the text, images, or the instructions/values for the javascript, the place for data is on the page.
- Keep the global namespace clean. With a little effort you can completely avoid adding any variables to the
windownamespace / global scope.
- Don't put code in the HTML It is tempting to put code in the page to start an animation `
. All good when it's a simple page but a source of headache, bugs, and unhappy clients when its get complicated
- When parts of your code starts to look repetitive it's a good sign that there is a better way.
- Remove event handlers when you are done. Event handlers use up resources.
- Always keep in mind your page shares the computer with dozens of others on the client's machine. Do your best to reduce the total load on their device.
The javascript
Always start your code with "use strict" it helps you avoid some very common bugs and bad coding styles and runs your code significantly faster.
"use strict"; // is valid as the first line of a script tag or the first
// line inside a function. Put anywhere else and it has no effect
window.addEventListener("load",function(){ // starting your code on the load
// event ensures that all the DOM
// tree is populated and readytry to define your event handlers as named functions because you need a function referance to remove the event if you need to.
function startButtonClick(){ // the start button eventWe only want this to play once. So remove the event from the button. When events are called this
references the element that triggered the event
this.removeEventListener("click",startButtonClick); // remove event
The spread operator is a short cut way of turning a array like list into an array. Be wary as IE 11 is still popular and does not support many ES6 features. If you use things like the spread operator you should consider using babel.js so that your code can run on legacy browsers.
var numberEl = [...document.getElementsByClassName('number')];
The numbers moving up is an animation. It will be control by requestAnimationFrame that will call the animate function at 60fps if possible, but that is not a guarantee. To ensure you get consistent animation on all devices use the supplied time the requestAnimationFrame callback supplies to time your animation.
You were using a interval of 1ms.The rule of thumb is 60fps or 16ms between display frames, updating content any higher than that rate will simply not be seen and thus will just waste resources.
var startTime; // holds that animation start time
function animateNumbers(time){ // time is the first argument of the
// requestAnimationFrame callback
This countSpeed controls how fast the numbers will increase per second. The animation will play at the same speed on all devices.
const countSpeed = 120; // count speed in increments per second
if(startTime === undefined){// if there is no start time then this must
// be first frame so make it the start time
startTime = time;
}
var seconds = (time - startTime) / 1000; //seconds from animation start
var count = countSpeed * seconds; // get the current count
done = true; // flag to indicate the animation is complete
numberEl.forEach(element => {
var max = Number(element.dataset.maxValue); // properties that you
// get from the page are strings.
// If you know it's a number let
// Javascript know
If the count is below max for any element flag the animation as not done.
if(count < max){
done = false;
}
Try to avoid setting text content with innerHTML as it can cause all sorts of problems that are avoided by telling the DOM it is only text you are adding
element.textContent = Math.min(max,Math.floor(count));
}
if(!done){ // continue animation until done
requestAnimationFrame(animateNumbers);
}
}
When ever you are animating anything on the page were you define every frame use requestAnimationFrame` it ensures that the animation is in sync with the hardware and any other page rendering. It also prevents updated conCode Snippets
"use strict"; // is valid as the first line of a script tag or the first
// line inside a function. Put anywhere else and it has no effect
window.addEventListener("load",function(){ // starting your code on the load
// event ensures that all the DOM
// tree is populated and readyfunction startButtonClick(){ // the start button eventthis.removeEventListener("click",startButtonClick); // remove eventvar numberEl = [...document.getElementsByClassName('number')];var startTime; // holds that animation start time
function animateNumbers(time){ // time is the first argument of the
// requestAnimationFrame callbackContext
StackExchange Code Review Q#147190, answer score: 3
Revisions (0)
No revisions yet.