18

这就是我想要完成的事情:当到达最后一张幻灯片时,fadeOut 最后一张幻灯片,然后 fadeIn 第一张幻灯片,然后 clearInterval (一切都适用于这部分)。现在我的问题是,如果 setInterval 不存在,我想再次
设置它,但我不知道如何实现:(我试图用 if 语句解决这个问题,但我的脚本根本不起作用!
所以我怎样才能重新开始我的间隔?谢谢!!
没有这样的 if 语句它工作正常:

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

});
4

5 回答 5

26

清除一个间隔后,您需要使用 重新启动它setInterval()

最好为您的功能setInterval()

var intervalID = null;

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

flag是一个boolean带有 value 的变量true/ falsetruewill execute setInterval()and falsewill clearInterval();

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

例如:

intervalManager(true, animate, 300);  // for setInterval

intervalManager(false);  // for clearInterval
于 2012-06-07T15:35:33.627 回答
4

只是示例

var myVar 
function myTimer() {
    var d = new Date();
    var t = d.toLocaleTimeString();
    document.getElementById("demo").innerHTML = t;
}

function myStopFunction() {
    clearInterval(myVar);
}
function myStartFunction() {
    myVar = setInterval(myTimer, 1000);
}
myStartFunction();
<p id="demo"></p>
<button onclick="myStopFunction()">Stop time</button>
<button onclick="myStartFunction()">Start time</button>

于 2018-07-15T13:27:56.107 回答
3

这是一个带有回调和间隔的实用程序对象,您可以使用它来启动和停止间隔。

   //simple utility object to start and stop an interval       
    var IntervalUtil = function(functionCall, interval){


        var intervalObj = 0,
            INTERVAL    = interval;

        var callback = functionCall;

        function startTimer(){
            console.log('start timer', intervalObj)
            if(intervalObj === 0){
                intervalObj = setInterval(callback, INTERVAL)
            }
        }   

        function stopTimer(){
            clearInterval(intervalObj);
            intervalObj = 0;
            console.log('timer stopped', intervalObj);
        }

        return {
            startTimer : startTimer,
            stopTimer  : stopTimer
        }

    };  

*你会这样使用它 *

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
    <meta name="author" content=""/>

    <title>Timer : setInterval()</title> 


    <style type="text/css">


    html, body, div, span, applet, object, iframe,
    h1, h2, h3, h4, h5, h6, p, blockquote, pre,
    a, abbr, acronym, address, big, cite, code,
    del, dfn, em, img, ins, kbd, q, s, samp,
    small, strike, strong, sub, sup, tt, var,
    b, u, i, center,
    dl, dt, dd, ol, ul, li,
    fieldset, form, label, legend,
    table, caption, tbody, tfoot, thead, tr, th, td,
    article, aside, canvas, details, embed, 
    figure, figcaption, footer, header, hgroup, 
    menu, nav, output, ruby, section, summary,
    time, mark, audio, video {
        margin: 0;
        padding: 0;
        border: 0;
        font-size: 100%;
        color:#000;
        line-height:1.3em;
        font: inherit;
        vertical-align: middle;
        font-family:arial;
        font-size:12px;
        outline:none;
    }

    a{
        outline:none;
        text-decoration:none;
        color:#145486;
    }
    a span{
        color:#145486;
    }

    h1{
        font-weight:normal;
        font-size:32px;
    }

    body{
        background:#efefef;
        text-align:center;
    }
    .content{
        width:400px;
        padding:20px;
        margin:10px auto;
        background:#fff;
        border:solid 1px #ebebeb;
        text-align:left;
    }

    #toggleTimer{
        color:#fff;
        font-size:10px;
        padding:2px 7px;
        display:inline-block;
        background:#357cb7;
        border:solid 1px #0c8af4;
    }

    #toggleTimer.running{
        background:#f14621;
        border:solid 1px #ff4c00;
    }

    #output{
        padding:7px;
        font-size:10px;
        border:dashed 1px #ebebeb;
        background:#f8f8f8;
        margin-left:10px;
        display:inline-block;
    }
    em{
        font-weight:bold;
    }

    </style>

</head>
<body>


<div class="content">

    <h1>Set Interval Code</h1>

    <a href="javascript:" id="toggleTimer" class="">Start Timer</a>

    <span id="output"></span>

    <br class="clear"/>

</div>


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>


<script type="text/javascript">

    $(document).ready(function(){
        var demo = new Demo();
    });


    var Demo = function(){

        var self = this;

        var START_TEXT = "Start Timer",
            STOP_TEXT  = "Stop Timer";

        var $toggle = $('#toggleTimer'),
            $output = $('#output');

        var count = 0;

        var intervalUtil;

        function init(){
            intervalUtil = new IntervalUtil(printMessage, 1000);
            setClickHandler();
            return self;
        }   

        function setClickHandler(){
            $toggle.click(toggleTimer)
        }

        function toggleTimer(){

            $toggle.toggleClass('running');

            if($toggle.hasClass('running')){
                $toggle.text(STOP_TEXT);
                intervalUtil.startTimer();
            }else{
                $toggle.text(START_TEXT);
                intervalUtil.stopTimer();
            }
        }

        function printMessage(){        
            $output.html("printMessage called <em>" + (count++) + "</em> times");
        }

        return init();

    }


    //simple utility object to start and stop an interval       
    var IntervalUtil = function(functionCall, interval){


        var intervalObj = 0,
            INTERVAL    = interval;

        var callback = functionCall;

        function startTimer(){
            console.log('start timer', intervalObj)
            if(intervalObj === 0){
                intervalObj = setInterval(callback, INTERVAL)
            }
        }   

        function stopTimer(){
            clearInterval(intervalObj);
            intervalObj = 0;
            console.log('timer stopped', intervalObj);
        }

        return {
            startTimer : startTimer,
            stopTimer  : stopTimer
        }

    };  

</script>


</body>
</html>
于 2012-06-07T16:30:35.060 回答
1

计时器的解决方案计数 15 秒然后转到主页,如果点击屏幕将计时器重置为开始。它可能对某人有用。(x 是触摸事件的计数器):

  var productInterval = null;
  var counterForGoToMainPage = 15;

  function startTimer(){
    counterForGoToMainPage--;

    if(counterForGoToMainPage == 0){
      clearInterval(productInterval);
      counterForGoToMainPage = 15;
      window.location.href = "/";
      }
  }

  function countTouches(event) {
  var x = event.touches.length;

    if(x == 1) { 
      clearInterval(productInterval);
      counterForGoToMainPage = 15;
      productInterval = setInterval(function(){
         startTimer();
      },1000);
    }
  }
于 2020-08-17T14:17:52.450 回答
0

在我的项目中(使用Sveltekit),我了解到您可以在函数之间循环setIntervalclearInterval使用let来定义 NodeJS 计时器:

$: number = 0 //The "$" sign, in this case, is used to a make reactive statement 

const changeValue = (e: any) => {
    let changingValue = setInterval(() => {
        number += 0.01
        if (number >= 0.2) {
            clearInterval(changingValue)
        }
    }, 4)
}, 
changeValueAgain = (e: any) => {
    let changingValue = setInterval(() => {
        number -= 0.01
        if (number <= 0) {
            clearInterval(changingValue)
        }
    }, 4)
}

(顺便说一下,我使用的是 Typescript)很简单,每次调用函数时,它都会创建一个新的 NodeJS 计时器,当某些条件为真时该计时器会被清除

e参数用于事件处理程序...

于 2022-02-27T02:44:27.977 回答