Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 767
Ziv Feldman Avatar asked May 18 '26 01:05

Ziv Feldman


2 Answers

When x reaches -400, you need to bring it back to -100 immediately, without an timeout cycle.

Try this:

var $post = $('.testi');
var x = -100;
var pause = 1500;
setIntervalX(function () {

    if ( x == -400 ){
        $('.testi').css('transition', '0s');
        $('.testi').css('transform', 'translateX(0)');
        x = -100;   
    }

    $post.css('transform', 'translateX(' + x + '%)');

    setTimeout(function(){
        $('.testi').css('transition', '1.5s ease');
        x = x - 100;
    }, 1500);

}, pause, 100);
like image 139
Jonathan Halpern Avatar answered May 19 '26 13:05

Jonathan Halpern


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);
like image 28
Ziv Feldman Avatar answered May 19 '26 15:05

Ziv Feldman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!