Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop a window.setInterval in javascript?

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); 
like image 303
Brian Avatar asked Sep 02 '11 05:09

Brian


2 Answers

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.

like image 180
Jeremy Avatar answered Oct 08 '22 14:10

Jeremy


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(); 
like image 36
Tim Avatar answered Oct 08 '22 12:10

Tim