I've reviewed the other clearInterval posts here for a clue as to why my code isn't functioning as intended. Despite my best efforts, I still can't get clearInterval to stop my count.
I'm trying to do something simple: have a count, increase by one until the stop button is pushed.
I have tried different, and incorrect variables, but I cannot find a working solution.
<p>Count Up:</p>
<p id="count">1</p>
<button onclick="clearInterval(current)">Stop</button>
<script>
var current = 1;
function animateValue(id) {
var obj = document.getElementById(id);
var current = parseInt(obj.innerHTML);
setInterval(function () {
current++;
obj.innerHTML = current;
}, 1000);
}
animateValue("count");
</script>
Store the value returned by setInterval in a variable and pass that as the parameter to clearInterval instead of counter:
<p>Count Up:</p>
<p id="count">1</p>
<button onclick="clearInterval(interval)">Stop</button>
<script>
var interval;
var current = 1;
function animateValue(id) {
var obj = document.getElementById(id);
var current = parseInt(obj.innerHTML);
interval = setInterval(function () {
current++;
obj.innerHTML = current;
}, 1000);
}
animateValue("count");
</script>
Related
let timer = document.querySelector("#timer");
var counter = 3;
function myFn() {
counter--
if (counter === -1) {
counter = 3
}
timer.innerText = counter
}
btn.onclick = function() {
text.innerHTML += 'clicked' + '<br>'
}
var myTimer = setInterval(myFn, 1000);
<div id="timer"></div>
<button id="btn">Button</button>
<div id="text"></div>
I'm trying with this small code to read the div#timer every second and check for a click condition in console.log() F12. It gives me different error in every way I try to do it.
let timer = document.querySelector("#timer");
let btn = document.querySelector("#btn");
setInterval(() => {
console.log(timer.textContent)
if (timer.textContent === '0') {
btn.click()
}
}, 1000);
Consider the following jQuery example.
$(function() {
var timer = 0;
var counter = 3;
var timeObj = $("#timer");
var btnObj = $("#btn");
var txtObj = $("#text");
var interval;
function myFn() {
if (--counter >= 0) {
txtObj.append("Clicked<br />");
} else {
clearInterval(interval);
}
}
interval = setInterval(function() {
timeObj.html(++timer);
}, 1000);
btnObj.click(myFn);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="timer">0</div>
<button id="btn">Button</button>
<div id="text"></div>
You will want to use setInterval() and not setTimeout().
The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
This method returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
See more: https://developer.mozilla.org/en-US/docs/Web/API/setInterval
Using the -- and ++ before the variable will also apply the change before it is used.
The decrement operator (--) decrements (subtracts one from) its operand and returns the value before or after the decrement, depending on where the operator is placed.
Adjusting the logic here can also ensure that the button click does allow the user to keep performing actions.
I have a map with multiple cities on it. I also have a loop showing the details of each city. I would like to completely stop the loop once I click on one of the cities.
I tried with: clearTimeout(loopIdx) but it didn't work. Could you please help me?! Cheers.
LOOP:
$(function() {
var $mapCol = $('.map-col');
var $mapBtn = $('.map-btn');
var $mapLoops = $('.map-loop');
var $btnLoops = $('.btn-loop');
loopIdx = (function _loop(idx) {
$mapCol.removeClass('active-map');
$mapBtn.removeClass('active-btn');
$mapLoops.removeClass('active-map').eq(idx).addClass('active-map');
$btnLoops.removeClass('active-btn').eq(idx).addClass('active-btn');
setTimeout(function() {
_loop((idx + 1) % $mapLoops.length);
}, 6000);
}(0));
});
BTN:
<div class="btn-loop">City</div>
Assign the result of setInterval() to a variable, and use that in the clearTimeout() call.
$(function() {
var $mapCol = $('.map-col');
var $mapBtn = $('.map-btn');
var $mapLoops = $('.map-loop');
var $btnLoops = $('.btn-loop');
var timer;
loopIdx = (function _loop(idx) {
$mapCol.removeClass('active-map');
$mapBtn.removeClass('active-btn');
$mapLoops.removeClass('active-map').eq(idx).addClass('active-map');
$btnLoops.removeClass('active-btn').eq(idx).addClass('active-btn');
timer = setTimeout(function() {
_loop((idx + 1) % $mapLoops.length);
}, 2000);
}(0));
$btnLoops.click(function() {
clearTimeout(timer);
});
});
.map-loop.active-map {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn-loop">City</div>
<div class="map-loop">1</div>
<div class="map-loop">2</div>
<div class="map-loop">3</div>
<div class="map-loop">4</div>
<div class="map-loop">5</div>
<div class="map-loop">6</div>
<div class="map-loop">7</div>
You need to access the timeoutID by name or identifier to clear it. (See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout.)
If you want loopIdx to be the identifier, you can use something like:
let needToClear = false;
let loopIdx = setTimeout(function(){}, 6000);
// ...state changes here...
if(needToClear){ clearTimeout(loopIdx); }
So, I got an infinite loop to work in this function using setInterval attached to an onClick. Problem is, I can't stop it using clearInterval in an onClick. I think this is because when I attach a clearInterval to an onClick, it kills a specific interval and not the function altogether. Is there anything I can do to kill all intervals through an onClick?
Here's my .js file and the calls I'm making are
input type="button" value="generate" onClick="generation();
input type="button" value="Infinite Loop!" onclick="setInterval('generation()',1000);"
input type="button" value="Reset" onclick="clearInterval(generation(),80;" // This one here is giving me trouble.
setInterval returns a handle, you need that handle so you can clear it
easiest, create a var for the handle in your html head, then in your onclick use the var
// in the head
var intervalHandle = null;
// in the onclick to set
intervalHandle = setInterval(....
// in the onclick to clear
clearInterval(intervalHandle);
http://www.w3schools.com/jsref/met_win_clearinterval.asp
clearInterval is applied on the return value of setInterval, like this:
var interval = null;
theSecondButton.onclick = function() {
if (interval === null) {
interval = setInterval(generation, 1000);
}
}
theThirdButton.onclick = function () {
if (interval !== null) {
clearInterval(interval);
interval = null;
}
}
Have generation(); call setTimeout to itself instead of setInterval. That was you can use a bit if logic in the function to prevent it from running setTimeout quite easily.
var genTimer
var stopGen = 0
function generation() {
clearTimeout(genTimer) ///stop additional clicks from initiating more timers
. . .
if(!stopGen) {
genTimer = setTimeout(function(){generation()},1000)
}
}
}
Live demo
This is all you need!
<script type="text/javascript">
var foo = setInterval(timer, 1000);
function timer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
$(document).on("click", "#stop_clock", function() {
clearInterval(foo);
$("#stop_clock").empty().append("Done!");
});
</script>
I just started learning coding with Javascript from scratch.
I have been trying to make a clock which can be stopped and started onclick.
I encountered a problem that really puzzles me:
When I click the "stop" button for the first time, the time does stop.
When I click the "start" button, the clock runs again.
The problem is :
When I click the "stop" button for the second time, the clock would
not stop.
Could you please kindly tell me why this happens?
var myclock = setInterval("showtime()", 1000);
function start() {
var myclock = setInterval("showtime()", 1000);
}
function stop() {
clearInterval(myclock);
}
function showtime() {
var time_now = new Date();
var local_time = time_now.toLocaleString();
document.getElementById("time").innerHTML = local_time;
}
<div id="time"></div>
<input type="button" value="start" onclick="start()">
<input type="button" value="stop" onclick="stop()">
Thank you for your time. :)
Case 1, w and r work with the same variable (same name and same location in memory) :
var x = 1;
function w () {
x = 2;
}
function r () {
return x;
}
w();
r(); // 2
Case 2, w and r work with different variables (same name but different locations in memory) :
var x = 1;
function w () {
var x = 2;
}
function r () {
return x;
}
w();
r(); // 1
In case 2, the var keyword creates a new variable that is local to w, while r keeps reading the old global variable. The same applies to your code. Because of the var keyword, start writes to a new local variable, while stop reads the old global variable. Remove var from start in order to update the global variable :
function start() {
myclock = setInterval("showtime()", 1000);
}
Here is a fixed and slightly improved version of your code snippet :
var myclock;
start();
function start() {
showtime();
myclock = setInterval(showtime, 1000);
}
function stop() {
clearInterval(myclock);
}
function showtime() {
var time_now = new Date();
var local_time = time_now.toLocaleString();
document.getElementById("time").innerHTML = local_time;
}
<input type="button" value="start" onclick="start()">
<input type="button" value="stop" onclick="stop()">
<span id="time"></span>
Look at your start function:
var myclock = setInterval(...
You're defining a new variable here, that isn't available to stop. In order for it to work the way you intended, remove the var:
myclock = setInterval(...
First, you're declaring the variable myclock again within your start function. When you refer myclock in stop you're referencing the variable outside, not the one within start. This means clearing does not clear the timer set in start.
Second, you're recreating the timer each time you click on start without clearing the previous one.
The fixed code would look something like this:
function showTime() {
var timeNow = Date();
var localTime = timeNow.toLocaleString();
document.getElementById("time").innerHTML = localTime;
}
var myClock;
function stop() {
clearInterval(myClock);
myClock = null;
}
function start() {
if (myClock)
return; // timer is already set. no need to recreate.
myClock = setInterval(showTime, 1000);
}
start();
<div id="time"></div>
<input type="button" value="start" onclick="start()" />
<input type="button" value="stop" onclick="stop()" />
So, I got an infinite loop to work in this function using setInterval attached to an onClick. Problem is, I can't stop it using clearInterval in an onClick. I think this is because when I attach a clearInterval to an onClick, it kills a specific interval and not the function altogether. Is there anything I can do to kill all intervals through an onClick?
Here's my .js file and the calls I'm making are
input type="button" value="generate" onClick="generation();
input type="button" value="Infinite Loop!" onclick="setInterval('generation()',1000);"
input type="button" value="Reset" onclick="clearInterval(generation(),80;" // This one here is giving me trouble.
setInterval returns a handle, you need that handle so you can clear it
easiest, create a var for the handle in your html head, then in your onclick use the var
// in the head
var intervalHandle = null;
// in the onclick to set
intervalHandle = setInterval(....
// in the onclick to clear
clearInterval(intervalHandle);
http://www.w3schools.com/jsref/met_win_clearinterval.asp
clearInterval is applied on the return value of setInterval, like this:
var interval = null;
theSecondButton.onclick = function() {
if (interval === null) {
interval = setInterval(generation, 1000);
}
}
theThirdButton.onclick = function () {
if (interval !== null) {
clearInterval(interval);
interval = null;
}
}
Have generation(); call setTimeout to itself instead of setInterval. That was you can use a bit if logic in the function to prevent it from running setTimeout quite easily.
var genTimer
var stopGen = 0
function generation() {
clearTimeout(genTimer) ///stop additional clicks from initiating more timers
. . .
if(!stopGen) {
genTimer = setTimeout(function(){generation()},1000)
}
}
}
Live demo
This is all you need!
<script type="text/javascript">
var foo = setInterval(timer, 1000);
function timer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
$(document).on("click", "#stop_clock", function() {
clearInterval(foo);
$("#stop_clock").empty().append("Done!");
});
</script>