Play and stop image sequences with pure Javascript

Did you ever try to play image sequences, maybe frame by frame animated cartoon or any sequences with Javascript?

Here we share you simple Javascript code to play it.

Basically, it works by manipulating image source for <img> element by time interval, for example 500 millisecond, repeatedly and the script loops and increment the frame number so the browser can show our images frame by frame based on interval we have set.

In this example, animation may be played with delay. But if graphic files is on local machine, animations will be started immediately.

Here is the source code:

<!DOCTYPE html>
			Simple image sequence player by Habibie

			var player;
			var played = false;

			function playSeq(firstframe, currentframe, lastframe, milliseconds, imageid, imagename, imageformat){
					player = setInterval(function(){
						document.getElementById(imageid).src = imagename+currentframe+imageformat; 
						if(currentframe == lastframe+1) currentframe = firstframe;
					}, milliseconds);
					played = true;

			function stopSeq(){
				played = false;
			<button onclick="playSeq(1,1,6,500,'myimg','sq','.jpg')">Play</button> <button onclick="stopSeq()">Stop</button>
			<img id="myimg" src="sq1.jpg" />

Recently I’ve published similar post about playing image sequences with JavaScript. But this time I’m using HTML5 Canvas to render the images. Read that post here: