javascript 单击时清除setInterval

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 单击时清除setInterval相关的知识,希望对你有一定的参考价值。


https://stackoverflow.com/questions/10442452/setinterval-and-clearinterval-when-cleared-does-not-animate-automatically

HTML

<div class="form-check">
  <label class="form-check-label">
    <input type="radio" class="form-check-input" id="day_choice" name="selected_time">Day
  </label>
</div>
<div class="form-check">
  <label class="form-check-label">
    <input type="radio" class="form-check-input" id="night_choice" name="selected_time">Night
  </label>
</div>




// JS
jQuery(document).ready( function() {
    // Start Timer and Date
    var IntID = runTimer(); // get ID for this Timer, later to be used when 
                            // disabling this timer
    dayOnClick() ;
    nightOnClick() ;

  // FUNCTIONS 
  function getStyleSheet() {
    ...
    // code that runs every 5 seconds in runTimer() 
  }



    // INIT TIMER
    function runTimer() {
        var i = setInterval( getStylesheet, 5000 );
        return i;
    }

    // STOP TIMER WITH REFERENCE ON INIT TIMER ABOVE
    function stopTimer() {
        clearInterval( IntID );
    }
    
    // DAY OPTION SELECTED
    function dayOnClick() {
        jQuery("#day_choice").click(function () {
            console.log( 'DAY CHOICE SELECTED' );
            // stop or pause the timer
            stopTimer() ;
            console.log('dayOnClick() - Timer Stopped') ;
            // disable/remove night.css and load day.css
            setDayStyleSheet() ;       
        });
    }

    // NIGHT OPTION SELECTED
    function nightOnClick() {
        jQuery("#night_choice").click(function () {
            console.log( 'NIGHT CHOICE SELECTED' );
            // stop or pause the timer
            stopTimer() ;
            console.log('nightOnClick() - Timer Stopped') ;
            // disable/remove day.css and load night.css
            setNightStyleSheet() ;
        });
    }
    
    
} ) ; //  END Document Ready


以上是关于javascript 单击时清除setInterval的主要内容,如果未能解决你的问题,请参考以下文章

请问javascript里var a=setinterval后在函数中清除再设定a返回值不停增加?

Javascript 在按钮单击时清除表单字段

单击javascript onclick时,php搜索不会清除

javascript 用 clearinterval 停止 setinterval

js 如何清除setinterval

JavaScript setInterval 后 CPU 使用率高