Reputation: 91
I'm doing a little mini-game and I need to do some animations (like frames per second), so far I manage to do this on my own:
var loadCount = 0;
var ticks = 15;
function loadingLoop() {
loadCount++;
}
switch (loadCount) {
case 1:
$("#img").attr("src", "src/images/cenario/img004.png");
break;
case 2:
$("#img").attr("src", "src/images/cenario/img005.png");
break;
case 3:
$("#img").attr("src", "src/images/cenario/img006.png");
break;
// etc.... //
}
setInterval(function(){
if (loadCount >= 6 && loadCount <= ticks){
loadingLoop();
if (loadCount === ticks) {
clearInterval();
}
console.log(loadCount);
}
}, 500);
So I would like to know if there is a better way to do this.
Upvotes: 0
Views: 71
Reputation: 36457
Because the numbering of your images is so clearly linked to the loadCount you could cut down the lines of code needed. Instead of having to spell out each instance in a switch you could simply have something like this:
$("#img").attr("src", "src/images/cenario/img" + (loadCount+3).toString().padStart(3, '0') + ".png");
padStart
takes a string which represents a number and pads it at the start with a character, in this case we've asked for 0s to be put at the front. The 3 indicates that we want 3 digits.
The other thing I noticed in your timing function is that you do not save your setInterval, but you try to clear it. Depending on what you are trying to do you probably need something like:
let interval = setInterval(function(){
if (loadCount >= 6 && loadCount <= ticks){
loadingLoop();
if (loadCount === ticks) {
clearInterval(interval);
}
console.log(loadCount);
}
}, 500);
Upvotes: 1