var images = new Array()
images = [
"images/1.svg",
"images/2.svg",
"images/3.svg",
"images/4.svg",
"images/5.svg",
"images/6.svg",
"images/7.svg",
"images/8.svg",
"images/9.svg",
"images/10.svg",
"images/11.svg",
"images/12.svg",
"images/13.svg",
"images/14.svg",
"images/15.svg",
"images/16.svg",
"images/17.svg",
"images/18.svg",
];
setInterval("Animate()", 100);
var x = 0;
function Animate() {
document.getElementById("img").src = images[x]
x ;
if (images.length == x) {
x = 0;
}
}
CodePudding user response:
This should help out. There's many ways you could organize and optimize this but this should give you a place to start.
<body>
<img src="images/1.svg">
<button onclick="toggle()">Play / Pause</button>
<script type="">
let
loop,
index = 0,
images = [
"images/1.svg", "images/2.svg", "images/3.svg", "images/4.svg", "images/5.svg", "images/6.svg", "images/7.svg", "images/8.svg",
"images/9.svg", "images/10.svg", "images/11.svg", "images/12.svg", "images/13.svg", "images/14.svg", "images/15.svg", "images/16.svg",
"images/17.svg", "images/18.svg"
];
function startLoop() {
loop = setInterval(() => {
document.querySelector('img').src = images[index];
index ;
// Loop images array
if (index % images.length === 0) {
index = 0;
}
}, 100);
}
function toggle() {
if (loop) {
clearInterval(loop);
loop = null;
} else {
startLoop();
}
}
startLoop();
</script>
</body>
CodePudding user response:
something more elaborate...
const
imgElm = document.getElementById('img-id')
, btOnOff = document.getElementById('bt-start-stop')
, images = [ 14, 15, 16, 17, 18, 19, 21, 22 ]
;
images.next = 1;
images.refintv = 0;
images.delay = 1000;
btOnOff.onclick = startLoop;
function startLoop()
{
newImage(); // immediate changing on click
btOnOff.textContent = 'stop';
btOnOff.onclick = stopLoop;
images.refintv = setInterval( newImage, images.delay);
function newImage()
{
imgElm.src = `https://picsum.photos/id/${images[images.next]}/300/200`;
images.next = images.next % images.length;
}
}
function stopLoop()
{
clearInterval(images.refintv);
btOnOff.textContent = 'start';
btOnOff.onclick = startLoop;
}
<button id="bt-start-stop">start</button>
<br><br>
<img id="img-id" src="https://picsum.photos/id/14/300/200" >