Search code examples
javascriptsettimeoutdelaysetinterval

setInterval setTimeout delay and pause for creating slide elements


I have 4 elements spread horizontally and I want to move them left every 3 sec, the thing that the 1st element and the 4th element are the same, so when we are at the 4th element I am changing back to the 1st without animation so the slides loop itself.

What happened is that the 1st/4th slide pauses twice the time. I am looking for a way to solve it, I tried to change the "pause" var during the interval through the "if" but that seems impossible.

I tried to setTimeout inside the interval but they both work parallel

function setIntervalX(callback, delay, repetitions) {
var x = 0;
var intervalID = window.setInterval(function () {

   callback();

   if (++x === repetitions) {
       window.clearInterval(intervalID);
   }
}, delay);}

than this

    var $post = $('.testi');
var x = -100;
var pause = 1500;
setIntervalX(function () {
    $post.css('transform', 'translateX(' + x + '%)');
    if ( x == -400 ){
        $('.testi').css('transition', '0s');
        $('.testi').css('transform', 'translateX(0)');
        x = -100;   
    }
    else {
    setTimeout(function(){
        $('.testi').css('transition', '1.5s ease');
        x = x - 100;
    }, 1500);
    }
}, pause, 100);

Solution

  • Thank you @Jonathan Halpern you make me think about that in a different way so I managed to solve it just made some changes

    var $post = $('.testi');
    var x = -100;
    var pause = 4000;
    setIntervalX(function () {
        if (x == -400){
            $post.css('transition', '0s ease');
            $post.css('transform', 'translateX(0)');
            x = -100;
        };
        setTimeout(function(){
            $('.testi').css('transition', '1s ease');
            $post.css('transform', 'translateX(' + x + '%)');
            x = x - 100;
        }, 150)
    }, pause, 100);