I read this question here “Is it faster to swap an img src or show/hide multiple images?”
The answer to the question has two options.
1) Alter the image source – Page loads faster, swapping consumes time.
2) Pre load images and then simply show/hide – Page loads a little slower, swapping is quicker
To my problem, I go with the second option as load time is 2nd priority for me. But is there best or most optimal way of writing the code?
Let’s say I keep getting numbers (10,11,15,25,13,19 etc randomly) from somewhere. I have to show that many images (small dots, 30 in number, each image about 1kb).. I also have the condition, every dot represents 1.5. So I have written the following code.
var dots = new Array(30);
function onBodyLoad() {
for(var j=0;j<30;j++)
dots[j] = document.getElementById("dotimg"+j);
}
//called by some method every second.
//argument: the value received from somewhere.
function updateImages(s) {
var x = Math.round(s);
var dotPos = x/1.5;
for(var i=0;i<dotPos;i++) {
dots[i].style.visibility='visible'; //show that many dots
document.getElementById('dot-val').textContent=s;//value received shown in span
}
for(var j=dotPos;j<30;j++) dots[j].style.visibility='hidden';//hide remaining dots
}
So if the value received is 25 in one second, 17 dots will be shown.. if in the next second the value received is 15, 10 dots will be shown, the rest will be hidden. Is there a better way of writing the above code?
First of all, move the
'dot-val'setting out of theforloop (You’re assigning the same value to it in each iteration of theforloop).Also, you can change the display states in 1 loop, saving a
for:Now, if you really want to trim your code, skip the temp
xvar, and use a Ternary operator: