setInterval, clearInterval not working - javascript

I have a requirement where I need to call a function repeatedly which calls setInterval. The problem I encountered is, if a function is generated(say every 1second) and it is set using setInterval; if we call setInterval twice/more without a clearInterval in between the function keeps on calling itself.
Ex :
<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<button onclick="myStartFunction()">Start time</button>
<button onclick="myStopFunction()">Stop time</button>
<script>
var myVar;
function myStartFunction(){
myVar = setInterval(function(){ myTimer() }, 1000);
}
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function myStopFunction() {
console.log(myVar);
clearInterval(myVar);
console.log(myVar);
}
</script>
</body>
</html>
If I click the Start Time button twice without clicking Stop time in between, the function doesn't stop. This is just an example of the scenario. Anyway to resolve this?

In your startFunction, just clear any existing intervals. Otherwise you are creating multiple intervals, but only storing a reference to the last interval created.
For example:
function myStartFunction(){
if(myVar) {
myStopFunction();
}
myVar = setInterval(function(){ myTimer() }, 1000);
}

You are overwriting the same myVar over and over again ... That means the stop function will only stop the last timer started. If you only want at most one setInteval to run, just add a call to the stop function before starting.

Related

JavaScript: Prevent setInterval Function From Running Until Button is Clicked

New to JS. I am trying to add a button to my page that says, "Start Game". When clicked, a countdown timer function starts executing, changing the text on the button every second from 10 down to 0, at which point the button will say "Time's Up!"
I have used the setInterval method to get the countdown timer working, but it starts running as soon as the page loads (run code snippet below to see in action).
I am trying to prevent it from running until the button is clicked. Here is my html button (with the property "onclick="startTimer()"), and the JS:
var timeleft = 10
var gameTimer = setInterval(startTimer, 1000);
function startTimer () {
if (timeleft <= 0) {
clearInterval(gameTimer);
document.getElementById("countdown").innerHTML = "Time's Up!";
} else {
document.getElementById("countdown").innerHTML = timeleft;
}
timeleft -=1;
};
<button id="countdown" onclick="startTimer()">Start Game</button>
I have tried adding a preventDefault to stop it from running on load, but nothing changed. How can I prevent the function from running until it hears the click event?
The core of the answer here is to move the invocation of setInterval() inside the function that's called when your button is clicked.
However, you really should re-factor this code a bit, both for readability as well as function. For example, I would expect startTimer() to do exactly what it says it does - start the timer, nothing more. However it seems that this function handles the decrement of timeleft.
The reason the suggestions in the comments above may not make sense at the moment is because you don't want to call setInterval() every time you want to decrease timeleft. Break this functionality out into discrete functions and save yourself the headache.
var timeleft = 10
var gameTimer;
function startTimer() {
gameTimer = setInterval(tick, 1000);
};
function tick() {
if (timeleft <= 0) {
clearInterval(gameTimer);
document.getElementById("countdown").innerHTML = "Time's Up!";
} else {
document.getElementById("countdown").innerHTML = timeleft;
}
timeleft -= 1;
}
<button id="countdown" onclick="startTimer()">Start Game</button>

how to make a timer run again and again in javascript

i want to make a 20 seconds countdown timer, when timer comes to zero it refreshes iframe. and then after refreshing iframe timer again comes to 20 seconds and after it comes 0 it again refreshes iframe. how can i do this, i have a js timer script which refreshes the iframe but i don't know how to make this script run again and again.
<script>
var tT;
var timer=20;
var stop;
$(document).ready(function(){
tT=document.getElementById('timer');
tT.value=timer;
stop=setInterval(function(){
if(timer>0){
timer--;
tT.value=timer;
}else{
clearInterval(stop);
}},1000);
setTimeout(function(){
document.getElementById('timer').value = timer;
document.getElementById('exchanger').src = document.getElementById('exchanger').src;
},20000);
});
</script>
Iframe :-
<input id="timer" value="20" type="text" size="2" readonly style="border:none;background:transparent;width:18px;text-align:center">
Use
setInterval(function, delay)
Here is the code for your function
(function(){
// do some stuff
setTimeout(arguments.callee, 20000);
})();
for reference, this question is already marked here on below link:
Calling a function every 60 seconds
Here is a sample code to help you out:
function loadlink() {
$('#iframeId')[0].contentWindow.location.reload(true);
}
loadlink(); // This will run on page load
var count = 1;
setInterval(function() {
$(".timer").text(count)
count++;
if (count == 20) {
loadlink() // this will run after every 20 seconds
count = 0;
}
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="timer"></div>
<iframe id="iframeId" class="myframe" name="myframe" src="http://google.com"></iframe>
I followed Albzi's suggestion (who commented on my question), I
Used setInterval instead of setTimeout and It worked!
the final script is:
var tT;
var timer=20;
var stop;
$(document).ready(function(){
tT=document.getElementById('div-ID');
tT.value=timer;
stop=setInterval(function(){
if(timer>0){
timer--;
tT.value=timer;
}else{clearInterval(stop);
}},1000);
setInterval(function(){ // I changed setTimeout here
document.getElementById('Iframe-ID').src = document.getElementById('Iframe-ID').src;
timer=20;
},20000);
});
and HTML: <div id="Div-ID"></div>
Iframe: <iframe id="Iframe-ID" src="source-url"></iframe>

Check if an Interval is running and viceversa

So i have a web app with basic authentication.
When im logged in, an Interval is set:
$("#login").click(function(e) {
var interval = setInterval(function(){myFunction();}, 2000); });
Then when im logged out i need to stop the interval:
$("#logout").click(function(e) {
if(typeof interval !== 'undefined') clearInterval(interval); });
But it doesnt work, i think the way to check if an interval exist is wrong...i can set the interval so it is running when im logged in, but i need to stop/clear it when i click on my Logout button and it doesnt...
PS. im using the interval to check "myFunction" automatically every 2 seconds, but maybe there is another way to accomplish this without an interval? thx
Your interval variable needs to be declared at a higher scope where it is available to both functions. As you have it now, it is a local variable that ONLY exists within the particular invocation of your event handler function. So, when the next event handler is called, that previous variable no longer exists. You may also want to protect against successive clicks on login:
var interval;
$("#login").click(function(e) {
if (!interval) {
interval = setInterval(function(){myFunction();}, 2000);
}
});
$("#logout").click(function(e) {
clearInterval(interval);
interval = null;
});
And, you don't need to check to see if interval is undefined. You can just call clearInterval() on it and clearInterval() will protect against any invalid argument you pass it.
Here is a simple example where your interval variable should be in global scope for both click events.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function myFunction(){
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
var interval;
$("#start").click(function(){
interval = setInterval(function(){
myFunction();
},2000);
});
$("#stop").click(function(){
clearInterval(interval);
});
});
</script>
</head>
<body>
<p id="demo"></p>
<button id="start">Start</button>
<button id="stop">Stop</button>
</body>
</html>

Call a javascript function after 5 sec of last key press

I have a form with an <input type=text /> and I want to call a javascript function after 5 seconds of the last key press, and every time a new key is pressed, this timer should reset and only call the function after 5 seconds.
How can I do this?
I'm using jQuery.
thanks!
Something like this should get you started:
var timeout;
$('input[type=text]').keypress(function() {
if(timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(myFunction, 5000)
})
This answer is great, but remember that you need to enable this code after the documents loads and after the function loads to clear the timeout.
Here is the complete code:
var timeout;
$(document).ready(function(){
$('input[type=text]').keypress(function() {
if(timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(myFunction, 5000);
});
});
var myFunction = new function() {
alert('myFunction is running');
clearTimeout(timeout); // this way will not run infinitely
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
Although it doesn't use jQuery, you could also have a look at the debouncing function described here.
Steve

Javascript Timing

I am trying to create a countdown using javascript. I got some code from here and modified it slighly.
<script type="text/javascript">
var c=10, t;
function timedCount() {
document.getElementById('txt').value=c;
c=c-1;
t=setInterval("timedCount()",1000);
}
function stopCount() {
clearInterval(t);
}
</script>
I need to call a countdown repeatedly until the user clicks on a link. It should countdown from 10 by 1 every second (10,9,8,7,6...0) until the link is clicked but it doesn't. Can anybody help me?
EDIT:
Does anyone know how to make the countdown restart once it hits 0?
Thank you in advance.
<script type="text/javascript">
var c=10;
var t;
function timedCount()
{
document.getElementById('txt').value=c;
c=c-1;
}
function startCount()
{
if (!t) t=setInterval("timedCount()",1000);
}
function stopCount()
{
clearInterval(t);
t=null;
}
</script>
Call startCount() in onload (or whatever) when you want the counter started. Note my startCount and stopCount don't create multiple interval timers.
Also, the element with id=txt needs to be an <input> or <textarea> box for your code to work. If it's a span, you should use document.getElementById('txt').innerHTML=c;
Finally, you might want timedCount() to stopCount() if c goes below zero. This is easy enough:
if (c <= 0) stopCount();

Categories

Resources