Stop setInterval call in JavaScript

前端 未结 16 1858
星月不相逢
星月不相逢 2020-11-21 05:00

I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?

I want the us

16条回答
  •  [愿得一人]
    2020-11-21 05:39

    Why not use a simpler approach? Add a class!

    Simply add a class that tells the interval not to do anything. For example: on hover.

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

     

    I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.

提交回复
热议问题