How do I clear this setInterval inside a function?

前端 未结 4 1431
眼角桃花
眼角桃花 2020-11-29 21:26

Normally, I’d set the interval to a variable and then clear it like var the_int = setInterval(); clearInterval(the_int); but for my code to work I put it in an

4条回答
  •  余生分开走
    2020-11-29 21:46

    Simplest way I could think of: add a class.

    Simply add a class (on any element) and check inside the interval if it's there. This is more reliable, customisable and cross-language than any other way, I believe.

    var i = 0;
    this.setInterval(function() {
      if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
        console.log('Counting...');
        $('#counter').html(i++); //just for explaining and showing
      } else {
        console.log('Stopped counting');
      }
    }, 500);
    
    /* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
    $('#counter').hover(function() { //mouse enter
        $(this).addClass('pauseInterval');
      },function() { //mouse leave
        $(this).removeClass('pauseInterval');
      }
    );
    
    /* Other example */
    $('#pauseInterval').click(function() {
      $('#counter').toggleClass('pauseInterval');
    });
    body {
      background-color: #eee;
      font-family: Calibri, Arial, sans-serif;
    }
    #counter {
      width: 50%;
      background: #ffffd;
      border: 2px solid #009afd;
      border-radius: 5px;
      padding: 5px;
      text-align: center;
      transition: .3s;
      margin: 0 auto;
    }
    #counter.pauseInterval {
      border-color: red;  
    }
    
    
    
    
    

     

提交回复
热议问题