开发者

How do I stop a window.setInterval in javascript?

开发者 https://www.devze.com 2023-04-01 06:04 出处:网络
I have a javascript function that is called every 2000ms.I want to stop this so I can have the user do other things on the page without it being called again.Is this possible?Here is the function that

I have a javascript function that is called every 2000ms. I want to stop this so I can have the user do other things on the page without it being called again. Is this possible? Here is the function that gets called every 2000ms:

window.setInterval(function getScreen (sid) {
      开发者_运维百科  if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {
            document.getElementById("refresh").innerHTML=xmlhttp.responseText;
          }
        }
        xmlhttp.open("POST","getScreen.php?sid="+<?php echo $sid; ?>,true);
        xmlhttp.send();
    },2000);


There's no built-in "pause" function, but you can stop it, and then start a new interval with the same function.

First, you need to capture the id returned by the call to setInterval:

let intervalId = window.setInterval(...);

Then when you want to stop it, call

 window.clearInterval(intervalId);

In your case I'd suggest defining setScreen by itself, and not inside of the call to setInterval. This way you can just use intervalId = window.setInterval(setScreen, 2000) when you want to resume it.


If you are using jQuery I would recommend the plugin jQuery Timer

var timer = $.timer(function() {
  alert('This message was sent by a timer.');
}, 2000, true);

Then you can easily pause the timer:

timer.pause();

And also resume it:

timer.play();


It's easier to do this by using window.setTimeout() instead of window.setInterval(). The following is adapted from my answer here.

Live demo: http://jsfiddle.net/timdown/Hkzex/

Code:

function RecurringTimer(callback, delay) {
    var timerId, start, remaining = delay;

    this.pause = function() {
        window.clearTimeout(timerId);
        remaining -= new Date() - start;
    };

    var resume = function() {
        start = new Date();
        timerId = window.setTimeout(function() {
            remaining = delay;
            resume();
            callback();
        }, remaining);
    };

    this.resume = resume;

    this.resume();
}


You can't pause an interval, but you can stop it and restart it.

var timer = setInterval(xx,tt);

// then some time later
clearInterval(timer);

You just have to capture the return value from setInterval() and call clearInterval() on it when you want to stop it.

The other way to do a repeat that you can stop repeating at any time is to do a repeated setTimeout() and then clearTimeout() to stop the next timer or just don't kick off the next setTimeout().


Do not re-declare anything

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

var i = 0;
window.setInterval(function() { //declare new function
  if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
    $('#showCount').html(i++); //just for explaining and showing
  }
}, 500);

$('#counter').hover(function() { //mouse enter
    $(this).addClass('pauseInterval');
    $('#counting').text('Stopped counting...');
  },function() { //mouse leave
    $(this).removeClass('pauseInterval');
    $('#counting').text('Counting...');
  }
);
<!-- 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>


<div id="counter"><span id="counting">Counting...</span> | <span id="showCount"></span></div>


Don't use setInterval(), especially when dealing with network (XHR/fetch) calls. There is no guarantee that your request will be finished on time but setTimeout() won't wait to fire up the next one opening more and more connections.

Simply use a setTimeout() that, with a simple if statement reschedules itself.


function updateContent() {
    someFunctionReturningAPromise()
        .then(() => {
            if (continue) {
                setTimeout(updateContent), 2000);
            }
        })
        .catch(e => console.log(e));
}

updateContent()


var intervalId = window.setInterval(code);
window.clearInterval(intervalId);
0

精彩评论

暂无评论...
验证码 换一张
取 消