clearInterval doesn't working - javascript

var started = false;
function start() {
var timer;
if(started === false) {
timer = setInterval(decrease, 1000);
started = true;
} else {
clearInterval(timer);
console.log("Should Clear");
}
}
The setInterval works but when I run the function again, it prints in the console that it should be removed. But it doesn't.

timer is declared inside your function, so when you call it again, it's a new instance.
Try declaring it outside the function, like this:
var started = false;
var timer;
function start() {
if(started === false) {
timer = setInterval(decrease, 1000);
started = true;
} else {
clearInterval(timer);
console.log("Should Clear");
}
}

timer gets reinitialized every time you call start so the second time you call it, it's not pointing to a timer id to clear.

use like this
var started = false;
var timer;
function start() {
if(started === false) {
timer = setInterval(decrease, 1000);
started = true;
} else {
clearInterval(timer);
console.log("Should Clear");
}
}

Because timer is in the scope of the function. So when you call it the second time, it is in another scope.

Related

clearTimeout not working when called in if statement

This code should run for 10 seconds before ending, however if you are running the function again before the 10 seconds are finished, it should clear theTimeout and start the 10 seconds over again
function start() {
let counter = 0;
let timeUp = true;
let hello;
setInterval(()=> {
counter++
console.log(counter)
},1000);
if (timeUp == false) {
clearTimeout(hello)
timeUp = true
console.log('should run again with new clock')
start()
} else {
console.log('new clock started')
timeUp = false;
hello = setTimeout(() => {
timeUp = true
console.log('end clock')
}, 10000);
};
};
When you call start() again, this new function has no reference to hello or timeUp
Try it like this:
let hello
let timeUp = true
function start() {
let counter = 0;
//let timeUp = true;
//let hello;
setInterval(()=> {
counter++
console.log(counter)
},1000);
if (timeUp == false) {
clearTimeout(hello)
timeUp = true
console.log('should run again with new clock')
start()
} else {
console.log('new clock started')
timeUp = false;
hello = setTimeout(() => {
timeUp = true
console.log('end clock')
}, 10000);
};
};
window.start = start
Inside your function start, timeUp is always set to true, and thus clearTimeout will never be called. The way you're doing things, you should make timeUp a global variable so the function has "memory" of if the time has been reached or not.
But why do you need to set two intervals? You're already keeping track of the number of seconds that have passed, so we can make use of that interval to determine when 10 seconds have passed. This simplifies things quite a bit, and allows us to get rid of the timeUp variable as well:
let interval;
function start() {
let counter = 0;
clearInterval(interval); // clear the previous interval
interval = setInterval(() => { // set a new interval
counter++;
if (counter == 10) {
console.log('end of clock');
clearInterval(interval);
}
console.log(counter);
}, 1000);
}
This achieves exactly what you want. Whenever start is called, it cancels the previous interval and creates a new one. Once 10 seconds have passed, it clears the interval.
Your approach is kind of misleading. I think a better approach would be to have a Timer Object that you can start:
function Timer() {
var self = {
// Declare a function to start it for a certain duration
start: function(duration){
self.counter = 0;
self.duration = duration;
clearTimeout(self.timeout); // Reset previous timeout if there is one
console.log("New counter starting.");
self.count();
},
// A function to count 1 by 1
count: function(){
console.log(self.counter);
self.counter++;
if(self.counter > self.duration){
console.log('Time is up.');
} else {
self.timeout = setTimeout(self.count, 1000); // not over yet
}
}
// and other functions like stop, pause, etc if needed
};
return self;
}
// Declare your Timer
var myTimer = new Timer();
// Start it on click
document.getElementById('start-btn').addEventListener('click', function(){
myTimer.start(10);
}, true);
<button id="start-btn">Start the timer</button>

Reset Counter OnClick

I have some code I am using to countdown from 15 after 15 secs passes it echoes "times over". The problem is if someone clicks twice there will be two counters in the same Div. I need the counter to reset if someone clicks on the button again.
function startCountDown(i, p, f) {
// store parameters
var pause = p;
var fn = f;
// make reference to div
var countDownObj = document.getElementById("countDown");
if (countDownObj == null) {
// error
alert("div not found, check your id");
// bail
return;
}
countDownObj.count = function (i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
// stop
return;
}
setTimeout(function () {
// repeat
countDownObj.count(i - 1);
},
pause);
}
// set it going
countDownObj.count(i);
}
function myFunction() {
alert("Time Over");
}
HTML:
<div id="TimerTitle">Timer</div>
<span id="countDown"></span>
<button onclick="startCountDown(15, 1000, myFunction);">
Start Time
</button>
Set the timeout as a global variable like so:
timer = setTimeout(function(){countDownObj.count(i - 1);},pause);
At the beginning of the function clear the timeout
clearTimeout(timer)
Code:
var timer;
function startCountDown(i, p, f) {
// store parameters
if(timer){clearTimeout(timer)}
var pause = p;
var fn = f;
// make reference to div
var countDownObj = document.getElementById("countDown");
if (countDownObj == null) {
// error
alert("div not found, check your id");
// bail
return;
}
countDownObj.count = function (i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
// stop
return;
}
timer = setTimeout(function(){countDownObj.count(i - 1);},pause);
}
// set it going
countDownObj.count(i);
}
function myFunction() {
alert("Time Over");
}
setTimeout returns an id to the timer that can be used with window.clearTimeout. The simplest solution would be to create a global timerId
var timerId;
...
function startCountDown(i, p, f) {
...
if (timerId) { window.clearTimeout(timerId); }
timerId = window.setTimeout(...);
https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout

clearTimeout not working in recursion function - javascript

Here is the code I am using. When ticks becomes equal to 5 the recursion function should stop clearing the mainThread timeout. Anybody please help.
var mainThread;
var ticks = 0;
function tickTimer() {
clearTimeout(mainThread);
if (ticks >= 5) {
endGame();
}
else {
mainThread = setTimeout(function () {
ticks++;
tickTimer();
}, 1000);
}
}
Let me know if any concerns.
Thank you in advance.
Try this instead:
function tickTimer() {
if (++ticks >= 5) {
clearInterval (mainThread);
endGame();
}
}
var mainThread = setInterval(tickTimer, 1000);
var ticks = 0;
you can try this. all you need to do is clear interval every time tickTimer function is called.
var mainThread = setInterval(tickTimer, 1000);
var ticks = 0;
function tickTimer() {
if (++ticks >= 5) {
clearInterval (mainThread);
endGame();
}
}
Did you declare mainThread ? Like this
var mainThread = null;
function tickTimer() {
clearTimeout(mainThread);
mainThread = null;
if (ticks >= 5) {
endGame();
}
else {
mainThread = setTimeout(function () {
ticks++;
tickTimer();
}, 1000);
}
}
And ticks++ not ticks--
Please try to replace ticks-- to ticks++
I've think just send your timer as argument
function tickTimer(timer) {
timer && clearTimeout(timer);
if (ticks >= 5) {
endGame();
}
else {
var timer = setTimeout(function () {
ticks--;
tickTimer(timer);
}, 1000);
}
}
Don't use global scope )))
I thing you should Initialize variable ticks as the function is triggered.

clearInterval does not work

I'm trying to create a simple countdown timer. It counts down from the number entered.
However, I'm trying to clear the interval when the counter gets to 0. At the moment it seems to acknowledge the if statement, but not clearInterval().
http://jsfiddle.net/tmyie/cf3Hd/
$('.click').click(function () {
$('input').empty();
var rawAmount = $('input').val();
var cleanAmount = parseInt(rawAmount) + 1;
var timer = function () {
cleanAmount--;
if (cleanAmount == 0) {
clearInterval(timer);
}
$('p').text(cleanAmount);
};
setInterval(timer, 500);
})
You're not saving the return value of the call to setInterval, which is the value that needs to be passed to clearInterval. Passing the timer handler does no good.
var timer, timerHandler = function () {
cleanAmount--;
if (cleanAmount == 0) {
clearInterval(timer);
}
$('p').text(cleanAmount);
};
timer = setInterval(timerHandler, 500);

setTimeout doesn't seem to be calling the function

The code worked great until I added the setTimeout. Now, no matter how I attempt to call the functions in setTimeout ( setTimeout(function(){fadeOut()},1000); setTimeout("fadeOut()",1000); etc ) it doesn't seem to get to the function at all.
I'm a Javascript newbie so any and all help is appreciated =]
javascript code:
var slideArray = ["slide1","slide2","slide3","slide4","slide5","slide6"];
var currentSlide = null;
var current = null;
var done = false;
function fade(newSlide)
{
if(currentSlide === null)
{
currentSlide = slideArray[0];
document.getElementById(currentSlide).style.opacity = 1.0;
for(var i=1;i<slideArray.length;i++)
document.getElementById(slideArray[i]).style.opacity = 0.0;
}
current = document.getElementById(currentSlide);
done = false;
do
{
window.setTimeout(fadeOut,1000);
} while(done == false);
currentSlide = newSlide;
current = document.getElementById(currentSlide);
done = false;
do
{
window.setTimeout(fadeIn,1000);
} while(done == false);
}
function fadeOut()
{
if(parseFloat(current.style.opacity)-0.1>.0000001)
{
current.style.opacity = parseFloat(current.style.opacity) -0.1;
done = false;
}
else
{
current.style.opacity = 0.0;
done = true;
}
}
function fadeIn()
{
if(0.9-parseFloat(current.style.opacity)>.0000001)
{
current.style.opacity = parseFloat(current.style.opacity)+0.1;
done = false;
}
else
{
current.style.opacity = 1.0;
done = true;
}
}
You can't use this structure:
do
{
window.setTimeout(fadeIn,1000);
} while(done == false);
Because the code in the setTimeout() runs sometime LATER, your value of done will NEVER be changed and this loop will run forever. And, as long as it runs, the setTimeout() never gets to fire either (because javascript is single threaded).
Instead, what you should do is launch the next setTimeout(fadeIn, 1000) from the fadeIn() function if you aren't done.
function fadeOut()
{
if(parseFloat(current.style.opacity)-0.1>.0000001)
{
current.style.opacity = parseFloat(current.style.opacity) -0.1;
setTimeout(fadeOut, 1000);
}
else
{
current.style.opacity = 0.0;
}
}
Remember that javascript is single-threaded, so your setTimeout'et functions will not be called until it is finished running the current script. Which will never happen since you're in a loop that's never gonna end (untill you're out of memory from all those setTimeout's). Just call setTimeout once and let the function return. And forget the idea of waiting for it to have happened.

Categories