How to pause javascript setInterval method for sometime and restart again?
How to pause javascript setInterval method for sometime and restart again?
I was using javascript setInterval method to display different divs after a regular interval of time. In between, I fell into the requirement of pausing the javascript setInterval method for sometime, do some stuff and restart it again. So, I repeatedly used setInterval and clearInterval to acheive my functionality.
I have 3 divs: div0 (green), div1 (yellow), div2 (red). All are overlapping each other. I am using setInterval to hide and show div1 and div2 after every second. if index = 4 or 6, I am showing red div else yellow div.
My requirement is that, When index becomes 8, I want to pause the setInterval for 5 seconds and till then show div0 (green) and afterwards resume the loop of setInterval until clearInterval is called.
Below is the code snippet for pausing and restarting setInterval method which is self explanatory.
var index=0;
var auto_refresh = 0;
$(document).ready(function(){
hideDiv();
auto_refresh = setInterval(function(){myTimer()}, 1000);
});
function myTimer()
{
index+=1;
if(index == 4 || index==6)
{
showDiv2();
}
else if (index == 8)
{
clearInterval(auto_refresh);
showDiv0();
auto_refresh = setInterval(function(){myTimer()}, 5000); //Now run after 5 seconds
}
else if (index > 12)
{
clearInterval(auto_refresh);
}
else
{
showDiv1();
}
}
function hideDiv()
{
document.getElementById("div0").style.visibility="hidden";
document.getElementById("div1").style.visibility="hidden";
document.getElementById("div2").style.visibility="hidden";
}
function showDiv0()
{
document.getElementById("div0").style.visibility="visible";
document.getElementById("div1").style.visibility="hidden";
document.getElementById("div2").style.visibility="hidden";
}
function showDiv1()
{
document.getElementById("div1").style.visibility="visible";
document.getElementById("div0").style.visibility="hidden";
document.getElementById("div2").style.visibility="hidden";
document.getElementById("div1").innerHTML=index;
}
function showDiv2()
{
document.getElementById("div2").style.visibility="visible";
document.getElementById("div0").style.visibility="hidden";
document.getElementById("div1").style.visibility="hidden";
document.getElementById("div2").innerHTML=index;
}
Relaxing for 5 seconds
This is div1
style="background:red;height:200px;width:200px;margin:0;position:absolute">
This is div2
Note: I had discussed this problem on stackoverflow and written the conclusion of the discussion here in this post.