clearTimeout() doesn't do what it's supposed to do - javascript

can anyone see what is wrong with the following code. it's supposed to display a count down from 30 and afterwards it refreshes the page with jquery's ajax load() function.
it works fine for the first or second count down but then the timer starts too count down to fastand sometimes goes to the negative numbers and does not stop at all
what am i doing wrong?
function refreshPage(){
stopRefresh();
$('div.yui-content').load('rdPage.aspx div.yui-content', doCalculation);
}
function stopRefresh(){
clearTimeout(timer);
clearTimeout(interval);
}
var count, timer, interval;
function startTimer(){
count = 30;
timer = setTimeout(refreshPage,count * 1000);
interval= setInterval(updateTimer,1000);
}
function updateTimer(){
count --;
$('#timerSpan').text("Refreshing in " + count + "s");
}
function doCalculation(){
negativeNumberRed();
startTimer();
}
edit: added doCalculations()

try
clearInterval(interval); instead of clearTimeout(interval);
Like this:
function stopRefresh(){
clearTimeout(timer);
clearInterval(interval);
}

Add a call to "stopRefresh()" to the "startTimer()" call.
function startTimer(){
stopRefresh();
count = 30;
timer = setTimeout(refreshPage,count * 1000);
interval= setInterval(updateTimer,1000);
}
My guess is that your code is managing to start up more than one instance of the interval timer. They'll all decrement the same counter.
edit ā€” oops - Dr. Strangelove is correct - you need to use "clearInterval()" on interval timers, and "clearTimeout()" for timeout timers. (edit again well, you probably should do that, but Chrome at least seems to stop interval timers via "clearTimeout()". Here is the jsfiddle.

I think it's better to only use the interval..
And when the count < 1 call refreshPage

Related

How do I use setInterval and clearInterval peoperly?

I want this timer to count down from 20 and stop at 0. timerFunction() is called on the click of a button.
var time=20;
var clicked=false;
function timeDisplay(){
document.getElementById("timer").innerHTML=
time;
}
function timerFunction(){
if(!clicked){
clicked=true;
if(time>0){
var i=setInterval(function(){
time--;
timeDisplay();
},1000);
}
else{
clearInterval(i);
}
}
}
Right now, the timer works, but it doesn't stop at zero and I don't understand why. Obviously I am very new to this, so any constructive criticism is appreciated.
Firstly your timerFunction is run only once. The statement if(time>0) will execute only once and it will always be true because time is 20 initially.
You ideally want your time variable to be checked after regular intervals. Something you can do inside your timeDisplay function. To enable that, you need to ensure that unique interval id (here intervalName) can be accessed by timeDisplay.
var time=20;
var clicked=false;
var intervalName = null;
function timeDisplay(){
document.getElementById("timer").innerHTML=
time;
if(time == 0){
clearInterval(intervalName);
}
}
function timerFunction(){
if(!clicked){
clicked=true;
intervalName = setInterval(function(){
time--;
timeDisplay();
},1000);
}
}
Note: I have replaced i with intervalName.
Your code has a logic flaw. When you call timerFunction, you set the interval. But since that function is run only once, it will never check your if clause and it also doesn't set the intervall multiple times, as it would have, would it get executed more than once.
Hint: try to check for the time inside the setIntervall callback. I'm not 100% sure, but you can probably clear the intervall inside aswell with something like clearIntervall(this). Maybe you wanna try this out. :)
Actually your if condition is checking for once and when the execution goes inside if it is not checking if condition again so you should have a condition inside interval function checking the value of time variable and clear interval.
`
var time=20;
var clicked=false;
function timeDisplay(){
document.getElementById("timer").innerHTML= time;
}
function timerFunction(){
if(!clicked){
clicked=true;
var i= setInterval(function(){
time--;
if(time == 0){
clearInterval(i);
}
timeDisplay();
},1000);
}
}
`

How to use setInterval to trigger a function so that I can stop it at some point?

So from what I have understood, setInterval() is used to call a function on repeat on regular intervals.
So basically it is a loop that executes a function forever periodically.
I am confused as to if I had to stop this execution at one point what would be the way to do it
for eg I am trying to print the message "hey" 3 times after 1 second each, but somehow it is printing it 3 times every second and is going on forever.
What can I do to stop it after a set number of times.
This is the code that I've been trying
var i = 3;
function message() {
console.log("hey");
}
while(i > 0) {
setInterval(message, 1000);
i = i - 1;
}
Your code is executing the setInterval thrice in the while loop, which is not needed.
Actually, setInterval does not work as a function call but actually registers a function to be called at some interval.
The setInterval() method will continue calling the function until clearInterval() i.e it is deregistered or the process is killed.
It should work like this
var i = 3;
var interval = setInterval(message, 1000);
function message() {
if (i === 0) {
clearInterval(interval);
}
console.log("hey");
i = i - 1;
}
To clear a setInterval, use global clearInterval method.
Example:
var timerId = setInterval(func, 500);
.... some code here....
clearInterval(timerId);
What can I do to stop it after a set number of times.
usually you don't use setInterval() for this, you use setTimeout().
Something like
var counter = 0;
function message() {
console.log("hey");
// we trigger the function again after a second, if not already done 3 times
if (counter < 3) {
setTimeout(message, 1000);
}
counter++;
}
// initial startup after a second, could be faster too
setTimeout(message, 1000);
The setInterval function calls the function indefinitely, whereas setTimeout calls the function once only.
Simply use clearInterval once the count runs out.
var i = 3;
function message(){
console.log("hey");
if (--i < 0) {
clearInterval(tmr);
}
}
var tmr = setInterval(message, 1000);
you have to assign that setInterval to a javascript variable to name it what for this setInterval, like this
var messageLog = setInterval(message, 1000);
After, in setInterval message function add this condition to clear the inverval whenever you want to clear.
function message(){
if(i>3) {
clearInterval(messageLog); // clearInterval is a javascript function to clear Intervals.
return null;
}
console.log("hey");
}
You can retrieve the timer when creating and clear it if needed.
var i=3;
var timer = setInterval(message,1000);
function message(){
console.log("hey");
iā€”-;
if(i==0)
clearInterval(timer)
}
a beginner here too,look for clearInterval method ...

Calling a function that is a clock from within another function accelerates the clock

I have three function: the first is a clock with setTimeout within, the second is a function called when the clock reach zero with a setInterval within and the third is a function called when the setInterval of the second is cleared and set another interval that when is cleared call the clock again. The chain of functions work but accelerate the clock a lot and I don't know why.
var secs=8;
function clock(){
secs--;
var timer=setTimeout(clock,1000);
document.getElementById('clock').innerHTML = 'Clock: ' + secs;
if(secs==0){
clearTimeout(timer);
noEvent();
}
}
function noEvent(){
var count=10;
var timer1=setInterval(function(){
// do something
count--;
if(count==0){
clearInterval(timer1);
repetition();
}
},200)
}
function repetition(){
var count=3;
var timer2=setInterval(function(){
// do something
count--;
if(count==0){
clearInterval(timer2);
secs=8;
clock();
}
},1000)
}
var index=0;
$("myId").click(function(){
var rand=this.id;
var check=(arrComputer[index]==rand); // arrComputer is an array
// generated by the computer
// by other function
if(check==true) {
// do something
clock();
}
}
The functions and the calls work but the clock that is set to 1 second (setTimeout(clock,1000)) go to one second in the first call, but in successives go much faster, so the variable secs go 8,7,6,5,...,0 but to a bigger speed: between 8 and 7 there is not 1000ms but may be 200ms.

interval keeps firing even though clearInterval has been called

I am trying to get a function to run 10 times with a pause inbetween each run, yet when I try to it repeats the function infinite times then after 10 times it pauses, and so on. Right now this is the code with the problem:
for(i=0;i<10;i++) {
console.log(i);
interval = setInterval(function() {console.log("Function ran");}, 1000);
}
window.clearInterval(interval);
Console:0123456789Function ran["Function ran" is repeated infinite times after "9"]
interval = setInterval(function() {console.log("Function ran");}, 1000);
This line creates a new interval-instance each time, which means you have created 10 intervals. At the end of the loop interval holds the id of the last interval that was created. Hence that's the only one you're clearing, and the other ones are still running.
To cancel the interval, you need to keep track of how many times the function has been invoked. One way you can do that is as follows:
function pauseAndRepeat(delay, iterations, func) {
var i = 0;
var interval = setInterval(function() {
func();
if(++i === iterations) {
clearInterval(interval);
}
}, delay);
}
Here we have a function that defines a counter (i) in its local scope. Then it creates an interval using a function that checks the counter to see if it should call your function (func) or clear the interval when it is done. interval will have been set when the interval-handler is actually called. In this case the handler is basically a closure since it is bound to the local scope of pauseAndRepeat.
Then you can invoke the function as follows:
pauseAndRepeat(1000, 10, function() {
console.log("Function ran");
});
This will print out Function ran ten times, pausing for a second each time.
setInterval is expected to run forever, on an interval. Every time you call setInterval here, you have a new infinite loop running your function every 10s, and as others have noted you only are canceling the last one.
You may do better with chained setTimeout calls:
var counter = 0;
function next() {
if (counter < 10) {
counter++;
setTimeout(function() {
console.log("Function ran");
next();
}, 1000);
}
}
next();
This chains delayed functions, setting a timeout for the next one after each runs. You can do something similar with setInterval and cancellation:
var counter = 0;
var intervalId = setInterval(function() {
console.log("Function ran");
if (++counter >= 10) {
clearInterval(intervalId);
}
}, 1000);
In both these cases the key issue is that you trigger the next run or cancel the interval within the callback function, not in synchronous code.

Change millisec for window.setInterval function

I used window.setInterval function. this function includes 3 arguments :
setInterval(code,millisec,lang)
I used that like this:
var counter = 1;
window.setInterval(function() {}, 1000 * ++counter);
but when first time set timer (second argument), is not changed and that act Like below code:
window.setInterval(function() {}, 1000);
please write correct code for change timer
Use window.setTimeout instead.
var delay = 1000;
function myTimer() {
// do whatever
window.setTimeout(myTimer, delay);
}
window.setTimeout(myTimer, delay);
You can manipulate delay in the body of your function.
Your problem is that javascript first execute '1000 * ++counter' once and then do not update the time interval.
You should try to use a timeout instead: https://developer.mozilla.org/en/DOM/window.setTimeout
And create a new time out with the new value every time your time out function is called.
Sounds like what you're after is not setInterval but rather setTimeout in a loop:
var counter = 1;
for (var i = 1; i <= 3; i++) {
window.setTimeout(function() {
alert("#" + counter);
counter++;
}, i * 1000);
}
This will execute three different "timers" one after the other.
Live test case: http://jsfiddle.net/86DRd/

Categories

Resources