简体   繁体   English

setInterval setTimeout延迟和暂停,用于创建幻灯片元素

[英]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. 我有4个水平展开的元素,我想每3秒向左移动一次,第1个元素和第4个元素是相同的,所以当我们在第4个元素时,我会变回第1个没有动画所以幻灯片循环本身。

What happened is that the 1st/4th slide pauses twice the time. 发生的事情是第1 /第4张幻灯片暂停了两倍的时间。 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. 我正在寻找一种方法来解决它,我试图通过“if”在间隔期间改变“暂停”变量,但这似乎是不可能的。

I tried to setTimeout inside the interval but they both work parallel 我尝试在区间内设置setTime,但它们都是并行的

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);

When x reaches -400, you need to bring it back to -100 immediately, without an timeout cycle. 当x达到-400时,你需要立即将它恢复到-100,没有超时周期。

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);

Thank you @Jonathan Halpern you make me think about that in a different way so I managed to solve it just made some changes 谢谢@Jonathan Halpern你让我以不同的方式思考,所以我设法解决它只是做了一些改变

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM