lundi 3 octobre 2022

Stop a random image using a button onclick using JavaScript

I am trying to make a simple game that loops through images in an array. If you click a button it will stop on an image and if you click the button again it will restart the image cycle. Here is my code. The loop of random images works, I just can't think of how to get the button to start/stop the image loop.

<div class="container">

    <button id="click"> STOP/START </button>
    <section></section>
    <br>
</div>

<script>
    const pics = [ 'url("./photo-1.jpg', 'url("./photo-2.jpg")', 'url("./photo-3.jpg")',
    'url("./photo-1.jpg', 'url("./photo-2.jpg")', 'url("./photo-3.jpg")',
    ];
  const pic = document.querySelector('section');

    function showImage() {
        var a = Math.floor(Math.random() * pics.length);
        var img = pics[a];
        pic.style.backgroundImage = img;
    }

    setInterval(showImage, 200);
    
</script>



Aucun commentaire:

Enregistrer un commentaire