SetTimeout and ClearTimeout (Doesn't clear at 0) - javascript

Maybe just sleep deprivation, but I can not understand what I'm doing wrong.
I'm calling a countDown function onLoad with setInterval.
Inside the countDown function I call clearTimeout when the number reaches 0 except it's called when it reaches 2.
What am I doing wrong?
Here's a snippet.
var interval, count = 5;
countDown()
interval = setInterval(countDown, 1000);
function countDown() {
document.body.innerHTML = count
count--
if(count === 0) {
clearInterval(interval)
document.body.innerHTML = "Redirecting to ....."
}
}

function countDown() {
document.body.innerHTML = count;
if(count === 0) {
clearInterval(interval)
document.body.innerHTML = "Redirecting to .....";
} else {
count--;
}
}

This is because you are decreasing the counter first and then evaluating, due to this 1 step is missed
var interval, count = 5;
countDown();
interval = setInterval(countDown, 1000);
function countDown() {
if(count === 0) {
clearInterval(interval)
document.body.innerHTML = "Redirecting to ....."
}
else
{
document.body.innerHTML = count
count--
}
}

Just put the count-- after the if statement, and a return; at the end of the if statement if you want to block the execution after that.
var interval, count = 5;
countDown()
interval = setInterval(countDown, 1000);
function countDown() {
document.body.innerHTML = count;
if(count === 0) {
clearInterval(interval);
document.body.innerHTML = "Redirecting to .....";
return;
}
count--
}

Related

Stop countdown timer at 0

I have a countdown timer that is working, but I cannot figure out how to get it to stop at 0.
Here's what I have:
let totalTime = 10;
let timeElapsed = 0;
let interval;
let currentQuestion = 0;
let currentAnswer = 0;
function startTimer() {
runTimer.textContent = totalTime;
interval = setInterval(function () {
totalTime--;
runTimer.textContent = totalTime;
}
, 1000);
if (interval <= 0) {
stopTimer();
}
}
function stopTimer() {
clearInterval(interval);
}
I tried creating an if statement to clearInterval once the timer reaches 0 but something is not right.
Just check if totalTime is <= 0 but inside the setInterval function like this.
function startTimer() {
runTimer.textContent = totalTime;
interval = setInterval(function () {
totalTime--;
runTimer.textContent = totalTime;
if (totalTime <= 0) {
stopTimer();
}
} , 1000);
}

clearInterval isn'tworking

I have to clear the interval but I don't know why it isn't working. Normally it schould be quite simple, but I just can't find out whats wrong.
if(data.groupStandings[0].active === true){
Tabelle();
var timerId = setInterval(countdown, 1000);
if(data.groupStandings[0].active === false){
clearInterval(timerId);
}
var timeLeft = 5;
function countdown() {
if (timeLeft < 0) {
clearTimeout(timerId);
code();
timeLeft--;
if(timeLeft <= -5){
timeLeft = 5;
}
} else {
code();
timeLeft--;
}
}
}
You're entering the case when
data.groupStandings[0].active === true
but trying to clear the interval on the value being false
var timerId = setInterval(countdown, 1000);
if (data.groupStandings[0].active === false) { // here
clearInterval(timerId);
}
so content of the if block will not be read at all unless data.groupStandings[0].active somehow changes it's state (which is not seen in the code)

Making a timer with code that can easily be reset

I'm making a shot clock for my school's basketball team. A shot clock is a timer that counts down from 24 seconds. I have the skeleton for the timer right now, but I need to have particular key bindings. The key bindings should allow me to rest, pause, and play the timer.
var count=24;
var counter=setInterval(timer, 1000);
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " secs";
}
I'm not sure what you meant by "rest" the timer, I interpret this as "pause", so:
Space = Pause / Play.
R = Reset.
var
count=24,
counter = setInterval(timer, 1000),
running = true;
function timer() {
count -= 1;
if (count <= 0) {
clearInterval(counter);
}
document.getElementById("timer").innerHTML = count + " secs";
}
window.addEventListener("keydown", function(e) {
switch(e.keyCode) {
case 32: // PLAY
running ? clearInterval(counter) : counter = setInterval(timer, 1000);
running = !running;
break;
case 82: // RESET
clearInterval(counter);
document.getElementById("timer").innerHTML = 24 + " secs";
count = 24;
running = false;
}
});
<div id="timer">24 secs</div>
I am not able to comment yet, but I recommend checking out this post Binding arrow keys in JS/jQuery
The linked post explains how to bind arrow keys using js/jquery. Using http://keycode.info/ you can find out the keycodes of your desired keys and replace the current values then continue to build your code from there.
Here is my code sample: http://codepen.io/anon/pen/vLvWJM
$(document).ready(function() {
var $timer = $('#timer');
var $timerStatus = $('#timerStatus');
var timerValue = 24;
var intervalId = null;
var timerStatus = 'stopped';
if(!$timer.length) {
throw 'This timer is missing a <div> element.';
}
$(document).keydown(function(k) {
if(k.which == 80) {
if(timerStatus === 'playing') {
clearInterval(intervalId);
timerStatus = 'stopped';
updateTimerStatus();
return;
}
intervalId = setInterval(function() {
playTimer();
timerStatus = 'playing';
updateTimerStatus();
}, 1000);
} else if(k.which == 82) {
clearInterval(intervalId);
resetTimer();
updateText();
timerStatus = 'stopped';
updateTimerStatus();
}
});
function playTimer() {
if(timerValue > 0) {
timerValue--;
updateText();
}
}
function resetTimer() {
timerValue = 24;
}
function updateText() {
$timer.html(timerValue);
}
function updateTimerStatus() {
$timerStatus.html(timerStatus);
}
});
<div id="timerStatus">stopped</div>
<div id="timer">24</div>

adding wait for a loop in javaScript

I wanna run a loop in javaScript like this
for (conditions) { do something; wait for a second
}
How to make the portion of the condition typed in bold (delaying the condition for a second) ?
timeTillWarning = 10;
setTimeout(looping, 1000);
function looping() {
if (count > 0) {
count--;
setTimeout(looping, 1000);
}
}
var i = 100;
var interval = setInterval(function () {
// do something
i--;
if (i == 0) clearInterval(interval);
}, 1000);

How do I correctly use setInterval and clearInterval to switch between two different functions?

For practice I am trying to display a number that increments from 0 - 9, then decrements from 9 - 0, and infinitely repeats.The code that I have so far seems to be close, but upon the second iteration the setInterval calls of my 2 respective functions countUp and countDown seem to be conflicting with each other, as the numbers displayed are not counting in the intended order... and then the browser crashes.Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Algorithm Test</title>
</head>
<body onload = "onloadFunctions();">
<script type = "text/javascript">
function onloadFunctions()
{
countUp();
setInterval(countUp, 200);
}
var count = 0;
function countUp()
{
document.getElementById("here").innerHTML = count;
count++;
if(count == 10)
{
clearInterval(this);
countDown();
setInterval(countDown, 200);
}
}
function countDown()
{
document.getElementById("here").innerHTML = count;
count--;
if(count == 0)
{
clearInterval(this);
countUp();
setInterval(countUp, 200);
}
}
</script>
From 0 - 9, up and down: <div id = "here"></div>
</body>
</html>
You need to capture the return value from setInterval( ... ) into a variable as that is the reference to the timer:
var interval;
var count = 0;
function onloadFunctions()
{
countUp();
interval = setInterval(countUp, 200);
}
/* ... code ... */
function countUp()
{
document.getElementById("here").innerHTML = count;
count++;
if(count === 10)
{
clearInterval(interval);
countUp();
interval = setInterval(countUp, 200);
}
}
#Claude, you are right, the other solution I proposed was too different from original code. This is another possible solution, using setInterval and switching functions:
function onloadFunctions() {
var count = 0;
var refId = null;
var target = document.getElementById("aux");
var countUp = function() {
target.innerHTML = count;
count ++;
if(count >= 9) {
window.clearInterval(refId);
refId = window.setInterval(countDown, 500);
}
}
var countDown = function() {
target.innerHTML = count;
count --;
if(count <= 0) {
window.clearInterval(refId);
refId = window.setInterval(countUp, 500);
}
}
refId = window.setInterval(countUp, 500);
}
clearInterval(this);. You can't do that. You need to save the return value from setInterval.
var interval;
function onloadFunctions()
{
countUp();
interval = setInterval(countUp, 200);
}
var count = 0;
function countUp()
{
document.getElementById("here").innerHTML = count;
count++;
if(count == 10)
{
clearInterval(interval);
countDown();
interval = setInterval(countDown, 200);
}
}
function countDown()
{
document.getElementById("here").innerHTML = count;
count--;
if(count == 0)
{
clearInterval(interval);
countUp();
interval = setInterval(countUp, 200);
}
}
try this:
...
<body onload = "onloadFunctions();">
<script>
var cup, cdown; // intervals
var count = 0,
here = document.getElementById("here");
function onloadFunctions() {
cup = setInterval(countUp, 200);
}
function countUp() {
here.innerHTML = count;
count++;
if(count === 10) {
clearInterval(cup);
cdown = setInterval(countDown, 200);
}
}
function countDown() {
here.innerHTML = count;
count--;
if(count === 0) {
clearInterval(cdown);
cup = setInterval(countUp, 200);
}
}
</script>
From 0 - 9, up and down: <div id = "here"></div>
</body>
you could also create a single reference to #here element. Use always === instead of ==
There are many ways to solve this problem, the following is my suggestion:
function onloadFunctions() {
var count = 0;
var delta = 1;
var target = document.getElementById("here");
var step = function() {
if(count <= 0) delta = 1;
if(count >= 9) delta = -1;
count += delta;
target.innerHTML = count;
window.setTimeout(step, 500);
}
step ();
}
PS: it's safer to use setTimeout than setInteval.
/** Tools */
const log = require('ololog').configure({
locate: false
})
let count = 0
let interval__UP
let interval__DOWN
function countUp () {
count++
log.green('countUp(): ', count)
if (count == 5) {
clearInterval(interval__UP)
interval__DOWN = setInterval(function () {
countDown()
}, 1000)
}
}
function countDown () {
count--
log.red('countDown(): ', count)
if (count == 0) {
clearInterval(interval__DOWN)
interval__UP = setInterval(function () {
countUp()
}, 3000)
}
}
function start () {
countUp()
log.cyan('start()')
interval__UP = setInterval(function () {
countUp()
}, 2000)
}
start()
Console Log shows it's working

Categories