Skip to content

How to move 3 pics elements using setInterval

In short, I’m trying to make something like this.

enter image description here

Here is my code. I need to use only setInterval and when resuming the pic moving action it starts from the last points not from the first one,

var e = document.querySelector(".img1");
        var img2 = document.querySelector(".img2");
        var img3 = document.querySelector(".img3");



        var x = setInterval(function() {
            var eLeftPos = e.offsetLeft;
            
            e.style.left = eLeftPos + 1 +'px';
            if (parseInt(e.style.left.split("px")[0]) == 400) {
                clearInterval(x);
                backWard();
            }
        }, 5);

        function backWard() {
            var eLeftPos = e.offsetLeft;
            //console.log(eLeftPos);
            setInterval(function() {
                e.style.left = (eLeftPos - 1) + 'px';
            }, 5);
        }

Answer

First of all, you need to define the direction of each images. And then if one reaches to end, change the direction to backward.

To give you the basic workflow, you can refer to the following code.

const image1 = {
    el: document.querySelector('.image1'),
    direction: 'left'
}
const image2 = {
    el: document.querySelector('.image2'),
    direction: 'down'
}
const image3 = {
    el: document.querySelector('.image3'),
    direction: 'right'
}

let timer = null;

function onStop() {
    if (timer) {
        clearInterval(timer);
        timer = null;
    }
}

function onResume() {
    timer = setInterval(() => {
        moveImage();
    }, 5);
}

function moveImage() {
   // here you can check if the images reach to end, then change the direction, otherwise, move the image according to the direction.
}