Clear interval and variables: clearinterval fails - javascript

I have this code: It's very simple. I create an interval, and that works fine, but when I clear it, that statement is the only thing that fails.
clearinterval(interval);
This line fails, dragging don the whole function with it. If I comment out this one line, discomodeoff() works perfectly, besides that my interval is still running.
var interval;
function discomodeon() {
interval = setInterval( 'flashtext()', 50 );
document.body.style.background = "#000000";
discoball.style.visibility="visible";
on.style.display="none";
off.style.display="block";
music.innerHTML = "<embed src='discomusic.mp3' autostart='true' loop='true' hidden='true'></embed>";
}
function discomodeoff() {
clearinterval(interval);
document.body.style.background = "#FFFFFF";
discoball.style.visibility="hidden";
on.style.display="block";
off.style.display="none";
music.innerHTML = "";
}
I'm not sure why it fails, but it causes discomodeoff() to fail.

It's clearInterval, not clearinterval.
function discomodeoff() {
clearInterval(interval);
document.body.style.background = "#FFFFFF";
discoball.style.visibility="hidden";
on.style.display="block";
off.style.display="none";
music.innerHTML = "";
}

Related

Counter speed increases when the start button is clicked again

When the start button is clicked once, everything works perfectly fine. However, when the start button is clicked multiple times (by accident for example), the speed of the counter increases and the stop button doesn't seem to work any more!
Why is this happening? And what can I do to prevent the start button (if clicked accidentally) from increasing the speed of the timer when it is already running?
<button id="startBtn" onclick="startTimer()">Start</button>
<button id="stopBtn" onclick="stopTimer()">Stop</button>
<h2 id="timer"></h2>
<script>
let myCounter
function startTimer() {
myCounter = setInterval(counter, 200);
}
function stopTimer() {
clearInterval(myCounter);
}
let i = 0;
function counter() {
document.getElementById("timer").innerHTML = i++;
}
</script>
Welcome to StackOverflow.
Within your question, it's unclear if you want the timer to reset if the user clicks the start button again, however with my answer, I came to the conclusion that you didn't.
Here's a modified version of startTimer() which utilizes a guard clause to check if an interval already exists (and if so, don't start again)
function startTimer() {
// Guard clause! If the counter exists, exit the function!
if(myCounter) {
return
}
myCounter = setInterval(counter, 200);
}
A tiny update of the stop function is also needed to set myCounter to null after the counter is stopped:
function stopTimer() {
clearInterval(myCounter);
// Set the counter to Null, because it is still declared even though it has no value! (try removing this line and see what happens when you hit start again)
myCounter = null;
}
Hope this helped :)
I added a variable that can helps you detect if the counter is already clicked or not, with the condition of that variable, you can have what you want, I edited your code.
<button id="startBtn" onclick="startTimer()">Start</button>
<button id="stopBtn" onclick="stopTimer()">Stop</button>
<h2 id="timer"></h2>
<script>
let myCounter
let clicked = false;
function startTimer() {
if(!clicked){
myCounter = setInterval(counter, 200);
}
clicked = true;
}
function stopTimer() {
if(clicked){
clearInterval(myCounter);
}
clicked = false;
}
let i = 0;
function counter() {
document.getElementById("timer").innerHTML = i++;
}
</script>
You could simply disable the start button once clicked, and re-enable it when the stop button is clicked.
let i = 0;
let myCounter;
let startBtn = document.getElementById('startBtn');
let stopBtn = document.getElementById('stopBtn');
let timer = document.getElementById('timer');
function startTimer() {
startBtn.disabled = true;
stopBtn.disabled = false;
myCounter = setInterval(counter, 200);
}
function stopTimer() {
startBtn.disabled = false;
stopBtn.disabled = true;
clearInterval(myCounter);
}
function counter() {
i++; timer.value = i;
}
startBtn.addEventListener('click', startTimer);
stopBtn.addEventListener('click', stopTimer);
<button id="startBtn">Start</button>
<button id="stopBtn" disabled>Stop</button>
<h2><output id="timer">0</output></h2>
As an added measure, you can even hide the disabled button so only the active one is shown.
button:disabled {
display: none;
}

Chrome Extensions: Javascript not not running clearInterval();

I'm trying the make a chrome extension in javascript. So far, my popup.js looks like this:
let bg;
let clock;
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('button1').addEventListener('click', butClicked);
bg = chrome.extension.getBackgroundPage();
//clock = document.getElementById("label1");
});
let timeStamp;
let isClockRunning = false;
function butClicked() {
let test = bg.getURL();
document.getElementById('test').innerHTML = test;
timeStamp = new Date();
isClockRunning = !isClockRunning;
runCheckTimer();
}
function runCheckTimer() {
var handle;
if(isClockRunning == true) {
handle = setInterval(updateClock, 1000);
}
else if(isClockRunning == false) {
clearInterval(handle);
handle = 0;
}
}
function updateClock() {
let seconds = bg.returnTimeSince(timeStamp);
document.getElementById("label1").innerHTML = "Seconds: " + seconds;
}
The program works just fine when I click the button once; it starts the timer. But when I click the button the second time, timeStamp gets set to 0, but the updateClock keeps running at the same interval; the interval doesn't get cleared even though I'm toggling the isClockRunning boolean. It's almost as if javascript is forgetting to run the else if part in runCheckTimer(). How can I fix this?
EDIT: On a sidenote, am I doing the timer thing the right way? Or is there a better way to do it? I basically want a timer to keep ticking every second since you've pressed the button, and then when you click it again it'll stop and reset to 0.
You have scoped handle to runCheckTimer. When runCheckTimer starts, it will create a new handle every time.
Move handle outside of the function.
var handle;
function runCheckTimer() {
if(isClockRunning == true) {
handle = setInterval(updateClock, 1000);
}
else if(isClockRunning == false) {
clearInterval(handle);
handle = 0;
}
}

Restarting setInterval in javaScript

var myImage = document.getElementById("mainImage");
var imageArray = ["_images/overlook.jpg","_images/winery_sign.jpg","_images/lunch.jpg",
"_images/bigSur.jpg","_images/flag_photo.jpg","_images/mission_look.jpg"];
var imageIndex = 0;
function changeImage() {
myImage.setAttribute("src",imageArray[imageIndex]);
imageIndex++;
if (imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
I tried to refactor this question restarting a setInterval, but couldn't get it right. Any help would be appreciated!
***Added context****
Basically I have a bunch of images that cycle through and stop upon clicking them. I'd like to restart the cycling upon clicking again...
var intervalHandle = setInterval(changeImage,5000);
//Basically I want a clearInterval on a click and then restart this changing image function it.
myImage.onclick = function(){
clearInterval(intervalHandle);
intervalHandle = setInterval(changeImage,5000);
};
I expect the problem is that setInterval doesn't fire immediately, and you're expecting it to call changeImage as soon as you click myImage. The first call to changeImage will be 5 seconds after clicking the image. You could do something like this to call changeImage immediately:
myImage.onclick = function () {
clearInterval(intervalHandle);
intervalHandle = setInterval(changeImage, 5000);
changeImage();
};
Another choice is to do away with intervals entirely (as with this answer) — intervals can queue up when the window isn't focused in some browsers, so you could have changeImage set its own timeouts:
var timeoutHandle = setTimeout(changeImage, 5000);
function changeImage() {
// ...
timeoutHandle = setTimeout(changeImage, 5000);
}
myImage.onclick = function () {
clearTimeout(timeoutHandle);
changeImage();
};
Basically I have a bunch of images that cycle through and stop upon clicking them. I'd like to restart the cycling upon clicking again...
Well why didn't you say so? ;)
So you want to start the interval if its not started, and stop it if it is started.
var intervalHandle = setInterval(changeImage, 5000); // start the interval by default
var running = true; // true if the interval is running, false if its not.
myImage.onclick = function(){
if (running) {
clearInterval(intervalHandle); // stop interval
running = false; // mark interval as stopped
} else {
intervalHandle = setInterval(changeImage, 5000); // start interval
running = true; // mark interval as started
changeImage(); // also change the image right now
}
};
the only reason why i think this would not work is if you define intervalHandle in a "dom ready" event or some other function so try putting it in global scope rather than defining it.
EDIT: sorry for the first reply it was indeed false beacause i didnt had full information of what you wanted to do so home this will help you
var intervalHandle = setInterval(changeImage,5000);
myImage.onclick = function(){
if (intervalHandle > -1) {
clearInterval(intervalHandle);
intervalHandle = -1;
} else {
intervalHandle = setInterval(changeImage,5000);
}
};

timer doesn't stop on buttonclick

I have trouble with timer in button click. When i click button startpause() method is called there i set start timer and stop timer. It works fine when I click button normally(one click after sometime another click) but when I click the button again and again speedly the timer starts to jump with 2-3 secs. Seems like more than one timer is running.. Anyone have any idea....?? here time is my timer method
function startpause() {
if(FLAG_CLICK) {
setTimeout(tim,1000);
FLAG_CLICK = false;
}
else {
clearTimeout(ti);
FLAG_CLICK = true;
}
}
function tim() {
time.innerHTML = t;
t = t + 1;
ti= setTimeout("tim()", 1000);
}
Try this:
// assuming you declared ti and t out here, cuz I hope they're not global
var t = 0;
var ti;
var running = false;
function startpause() {
clearTimeout(ti);
if(!running) {
ti = setTimeout(tim,1000);
running = true;
} else {
running = false;
}
}
function tim() {
time.innerHTML = t;
t = t + 1;
ti = setTimeout(tim,1000);
}
You can read more about the .setTimeout() here: https://developer.mozilla.org/en/docs/DOM/window.setTimeout
Also, see the jsfiddle I just created: http://jsfiddle.net/4BMhd/
You need to store setTimeout somewhere in order to manipulate it later.
var myVar;
function myFunction()
{
myVar=setTimeout(function(){alert("Hello")},3000);
}
function myStopFunction()
{
clearTimeout(myVar);
}
ref http://www.w3schools.com/js/js_timing.asp
Maybe you must change this:
if(FLAG_CLICK) {
setTimeout(tim,1000);
FLAG_CLICK = false;
}
to:
if(FLAG_CLICK) {
tim();
FLAG_CLICK = false;
}
It seems works for me normally

Timer won't die javascript

I am doing some long polling.. and I have a function to make a button blink when a certain statement is true.. Here it is:
function blinking(object, x) {
console.log(x);
if(x>0){
var existing_timer = object.data('clock');
if (existing_timer){
clearInterval(existing_timer);
}
timer = setInterval(blink, 10);
function blink() {
object.fadeOut(400, function() {
object.fadeIn(400);
});
}
}
}
Now.. Notice the timer being set as 'timer'. When someone does something that makes the statement false (making x=0), I want the timer to stop making the button blink when it sees that x=0. This may sound easy but I have tried everything ha.
I've been researching and trying different things, but It doesn't seem to work.
If your variable timer is global, then you should be able to clear the interval using that:
clearInterval(timer);
The integer returned from the setInterval is unique to that timer, so that is what you need to clear.
Here's a simple implementation.
http://jsfiddle.net/AQgBc/
var $led = $('#led'),
blinkState = 0,
blinkTimer,
blinkDuration = 300,
blink = function () {
if (blinkState) {
$led.toggleClass('on');
}
console.log('blink');
blinkTimer = setTimeout(blink, blinkDuration);
};
$('button').on('click', function () {
blinkState = (blinkState) ? 0 : 1;
});
blink();
I just wrote my own without duplicating yours, but the most relevant issue, I think, is just using a setTimeout rather than worrying about a setInterval and clearing that interval.
Edit in response to comment:
If you want it to blink until a user action, then stop polling, it's even simpler.
http://jsfiddle.net/AQgBc/1/
var $led = $('#led'),
blinkState = 1,
blinkTimer,
blinkDuration = 300,
blink = function () {
if (blinkState) {
console.log('blink');
$led.toggleClass('on');
blinkTimer = setTimeout(blink, blinkDuration);
}
};
$('button').on('click', function () {
blinkState = (blinkState) ? 0 : 1;
});
blink();

Categories