使用Deferred方法确保函数完成?

时间:2016-09-10 15:21:35

标签: jquery

所以我有一个滑块设置,一切正常,直到我在幻灯片完成动画之前多次开始点击上一个和下一个按钮(我使用slideMove函数执行此操作)...我已经阅读了关于延期方法,但我不能为我的生活弄清楚如何使这个工作......或者即使它是要走的路......有谁能看到如何解决这个问题?

我会将它添加到jfiddle,但我通过ajax调用我的图像。

$(document).ready(function(){

var folder = "imgs/";
var imgArr = [];
var imgPath = [];

function loadImages() {
  //my ajax is here calling the images into the array
}


$.when( loadImages() ).done(function(a1){

//responsive width  
var theWidth = $(window).width();
$('#autoSlider , .moveLeft , .sliderContainer ').css({'width': theWidth });
$( window ).resize(function() { 
  theWidth = $(this).width();
  $('#autoSlider , .moveLeft , .sliderContainer ').css({'width': theWidth });
  $('.shrink').css({'width': theWidth - 40 });
  console.log(theWidth);
});

var slideTime = 3000;
var imgInd = 0;
var shrink = {'width': theWidth - 40, 'height': 'calc(80vh - 20px)', 'left': '20px', 'bottom': '25px'};


prevNext = 0; //if this is 0 go to next if it is 1 goto prev

 var slideMove = function(){

    var turnary = (prevNext === 0)? imgInd++ : imgInd-- ; 

    if ( imgInd >= imgArr.length ){ imgInd = 0; }
    if ( imgInd < 0 ){ imgInd = imgArr.length - 1; }
    clearInterval(auto);
    $('.imageholder').prepend('<div class = "moveLeft"></div>');
    $('.moveLeft').css({'width': theWidth });

    if(prevNext === 0){$('.moveLeft').css({ 'background-image': 'url(' + imgPath[imgInd] + ')' , 'left' : theWidth });}
    else if(prevNext === 1){$('.moveLeft').css({ 'background-image': 'url(' + imgPath[imgInd] + ')' , 'left' : 0 - theWidth });}

    prevNext = 0;
    $('#autoSlider').addClass( "shrink" , 200);
    $('.moveLeft').animate({ 'left' : '0px' }, "slow" , function(){ 
        $('#autoSlider').css({ 'background-image': 'url(' + imgPath[imgInd] + ')'});
        $('#autoSlider').removeClass( "shrink");
        $('.moveLeft').remove(); 

        auto = setInterval(slideMove, slideTime);
    }); 

};

$('#autoSlider').css({ 'background-image': 'url(' + imgPath[imgInd] + ')'});

//下面是prev和next按钮的监听器

$('#sliderNext').on( 'click' , function(){ prevNext = 0; slideMove(); });
$('#sliderPrev').on( 'click' , function(){ prevNext = 1; slideMove(); });


var auto = setInterval(slideMove, slideTime);

$('#autoSlider').mouseenter(function(event) {
    clearInterval(auto);
}).mouseleave(function(event) {
    auto = setInterval(slideMove, slideTime);
});


});

0 个答案:

没有答案