I'm creating a 2D platformer game with HTML5 canvas and javascript. I'm having a bit of a struggle with animations. Currently I animate by getting preloaded images from an array, and the code is really simple, in player.update() I call a function that does this:

There are a couple of problems with this one: When the player does 2 actions that require animating at the same time, animation speed doubles. Apparently this.counter++ is working twice at the same time. I imagine that if I start animating multiple sprites with this, the animation speed will multiply by the amount of sprites. Other issue is that I couldn't make the animation run only once instead of looping while key is held down.

Someone told me that I should create a function Animation(animation id, isLooped boolean) and the use something like player.sprite = new Animation("explode", false) but I don't know how to make it work.

In short, there is probably an easy way to solve this. Create an object that represents an Animation. This is usually just an ordered list of frames and durations.

Create a separate object to store the playback information, in other words, how "far" into an animation you have played. I recommend using a time-based animation scheme. This way, you can play an animation by advancing time and you should not run into problems with double speed.

The update of the anim should take as argument the current time or actual frame duration (timers are not so acurate, and requestAnimationFrame can trigger any time).
You can compute the time with Date.now() or even better window.performance.now().
(For reasons too long to explain here, the really best solution is to have your own game time.)
Each frame should also be assigned a given time. Most simple way is to have the same duration for each frame, and have an array that allows you to repeat some frame to shape your animation as you want :