Stop setInterval call in JavaScript

前端 未结 16 1717
星月不相逢
星月不相逢 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:35

    In nodeJS you can you use the "this" special keyword within the setInterval function.

    You can use this this keyword to clearInterval, and here is an example:

    setInterval(
        function clear() {
                clearInterval(this) 
           return clear;
        }()
    , 1000)
    

    When you print the value of this special keyword within the function you outpout a Timeout object Timeout {...}

    0 讨论(0)
  • 2020-11-21 05:35
    var keepGoing = true;
    setInterval(function () {
         if (keepGoing) {
            //DO YOUR STUFF HERE            
            console.log(i);
         }
         //YOU CAN CHANGE 'keepGoing' HERE
      }, 500);
    

    You can also stop the interval by adding an event listener to let's say a button with the ID "stop-interval":

    $('buuton#stop-interval').click(function(){
       keepGoing = false;
    });
    

    HTML:

    <button id="stop-interval">Stop Interval</button>
    

    Note: The interval will still be executed, nothing will happen though.

    0 讨论(0)
  • 2020-11-21 05:36

    The answers above have already explained how setInterval returns a handle, and how this handle is used to cancel the Interval timer.

    Some architectural considerations:

    Please do not use "scope-less" variables. The safest way is to use the attribute of a DOM object. The easiest place would be "document". If the refresher is started by a start/stop button, you can use the button itself:

    <a onclick="start(this);">Start</a>
    
    <script>
    function start(d){
        if (d.interval){
            clearInterval(d.interval);
            d.innerHTML='Start';
        } else {
            d.interval=setInterval(function(){
              //refresh here
            },10000);
            d.innerHTML='Stop';
        }
    }
    </script>
    

    Since the function is defined inside the button click handler, you don't have to define it again. The timer can be resumed if the button is clicked on again.

    0 讨论(0)
  • 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;  
    }
    <!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    
    <p id="counter">&nbsp;</p>
    <button id="pauseInterval">Pause</button></p>

    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.

    0 讨论(0)
  • 2020-11-21 05:42

    Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (for Node and browser).

    // Timer with 1000ms (1 second) base interval resolution.
    const timer = new TaskTimer(1000);
    
    // Add task(s) based on tick intervals.
    timer.add({
        id: 'job1',         // unique id of the task
        tickInterval: 5,    // run every 5 ticks (5 x interval = 5000 ms)
        totalRuns: 10,      // run 10 times only. (omit for unlimited times)
        callback(task) {
            // code to be executed on each run
            console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
            // stop the timer anytime you like
            if (someCondition()) timer.stop();
            // or simply remove this task if you have others
            if (someCondition()) timer.remove(task.id);
        }
    });
    
    // Start the timer
    timer.start();
    

    In your case, when users click for disturbing the data-refresh; you can also call timer.pause() then timer.resume() if they need to re-enable.

    See more here.

    0 讨论(0)
  • 2020-11-21 05:44

    The clearInterval() method can be used to clear a timer set with the setInterval() method.

    setInterval always returns a ID value. This value can be passed in clearInterval() to stop the timer. Here is an example of timer starting from 30 and stops when it becomes 0.

      let time = 30;
      const timeValue = setInterval((interval) => {
      time = this.time - 1;
      if (time <= 0) {
        clearInterval(timeValue);
      }
    }, 1000);
    
    0 讨论(0)
提交回复
热议问题