javascript – 如何清除间隔并重新设置?

这是我要完成的:当最后一张幻灯片到达fadeOut最后一张幻灯片,然后淡入第一张幻灯片,然后clearInterval(一切适用于此部分).现在我的问题是,如果它不存在,我想再setInterval,但我不知道如何使它发生:(我已经尝试解决这个,如果statment,但我的脚本根本不工作!如何重新启动我的间隔再次?谢谢你,如果没有这样的声明它工作正常:
if(!intervalID){
    intervalID = setInterval(animate,5000);
}

这是我到目前为止

$(document).ready(function() {
  /*check if intervalID don't exists messes UP!!*/
  if (!intervalID) {
    intervalID = setInterval(animate,5000);
  }

  //Hide everything except first slide and controls

  $('.slidewrap div:not(.slidewrap div:first,.slidewrap .slide_controls)').hide();

  var animate = function() {

    /*if .pagination_active is last removeClass and addClass to .pagination_active 
             first li tag*/

    if ($('.pagination_active').is($('.slide_controls ul li:last'))) {
      $('.pagination_active').removeClass('pagination_active');
      $('.slide_controls ul li:first').addClass('pagination_active');
    } else {
      $('.pagination_active').removeClass('pagination_active').next().addClass('pagination_active');
    }

    /*if div.active is last fadeOut and add .active class 
             to the first div and fadeIn FirsT div then CLEAR INTERVAL and set intervalID to zero */

    if ($('.active').is($('.slidewrap div:last'))) {
      $('.active').fadeOut(1000).removeClass('active');
      $('.slidewrap div:first').addClass('active').fadeIn(1000,function() {
        clearInterval(intervalID);
        intervalID = 0;

      });
    }

    //OR .active fadeOut and next div fadeIn
    else {
      $('.active').fadeOut(1000).next().fadeIn(1000,function() {
        $('.slidewrap div.active').removeClass('active').next('div').addClass('active');

      });
    }

  }

  var intervalID;
  intervalID = setInterval(animate,3000);

});

解决方法

清除一段时间后,您需要再次使用setInterval()启动它.

最好为你的setInterval()

var intervalID = null;

function intervalManager(flag,animate,time) {
   if(flag)
     intervalID =  setInterval(animate,time);
   else
     clearInterval(intervalID);
}

这里flag是一个值为true / false的布尔变量. true将执行setInterval(),false将clearInterval();

现在,您可以根据需要使用上述功能.

例如:

intervalManager(true,300);  // for setInterval

intervalManager(false);  // for clearInterval

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...