clearInterval doesn't works and increases interval speed - javascript

Im making a blackjack game which contains a timer. Timer should restart if player decides to draw a new card. When i press draw button it does reset but increments interval speed by 1.
const createCountDown = (isPlayerDrawed = false) => {
delay = 10;
let Timer = document.getElementById('timer');
if (isPlayerDrawed == true) {
delay = 10;
clearInterval(timer);
createCountDown(false);
} else {
let timer = setInterval(() => {
if (delay <= 0) {
clearInterval(timer);
stay();
} else {
delay--;
Timer.innerHTML = delay;
}
}, 1000)
console.log(timer)
}
}
How can i fix this problem ?

const createCountDown = (isPlayerDrawed = false, delay) => {
counter = delay;
let Timer = document.getElementById('timer');
let interval = null
if (isPlayerDrawed === true) {
clearInterval(interval);
} else {
interval = setInterval(() => {
Timer.innerHTML = counter;
if (counter <= 0) {
clearInterval(interval);
stay();
} else {
counter--;
}
}, 1000)
}
}
changing function like this worked for me.

Your let timer is only scoped to the else block. Other references will refer to a global variable.
Here is how you can make it work:
let Timer = document.getElementById('timer');
const stay = () => Timer.textContent = "timer expired!";
const createCountDown = (function () {
let delay, timer;
function reset() {
delay = 10;
clearInterval(timer);
timer = 0;
Timer.textContent = "";
}
reset();
return function () {
reset();
Timer.textContent = delay;
timer = setInterval(() => {
if (delay <= 0) {
reset();
stay();
} else {
delay--;
Timer.textContent = delay;
}
}, 1000);
}
})();
// Optionally start timer immediately:
createCountDown();
document.getElementById('draw').addEventListener("click", createCountDown);
<button id="draw">Draw</button>
<p id="timer"></p>

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);
}

Trying to format timer like 5:00 instead of 500

I'm trying to make a timer and it works fine really.
How am I supposed to put a : between the numbers, is their an easy way to do it?
It currently displays like this 500 and counts down and works fine. I want it to display like this 5:00 is there any easy way just to put that one character quickly in?
I just want it to countdown from five minutes to zero.
Or would I have to format the timer differently to be able to do that.
var timer;
var time = 500;
function startTimer() {
timer = setInterval(countdown, 1000);
}
function countdown() {
time--;
var timeText = document.getElementById('timer');
if (time === 499) {
time = 459;
} else if (time === 399) {
time = 359;
} else if (time === 299) {
time = 259;
} else if (time === 199) {
time = 159;
} else if (time === 99) {
time = 59;
}
if (time > 0) {
timeText.innerHTML = time;
} else {
clearInterval(timer);
timeText.innerHTML = 'end';
}
}
function nextPage() {
clearInterval(timer);
sessionStorage.setItem('timerem', time);
window.open('02page2.html', "_self");
}
function loadTimer() {
var timeText = document.getElementById('timer');
if (sessionStorage.getItem('timerem') === null) {
timeText.innerHTML = 'ERROR';
} else {
time = sessionStorage.getItem('timerem');
timeText.innerHTML = time;
timer = setInterval(countdown, 1000);
}
}
startTimer()
<span id="timer"></span>
How about
const formatTime = num => (num/100).toFixed(2).replace(".",":");
const formatTime = num => (num/100).toFixed(2).replace(".",":");
var timer;
var time = 500;
function startTimer() {
timer = setInterval(countdown, 1000);
}
function countdown() {
time--;
var timeText = document.getElementById('timer');
if (time === 499) {
time = 459;
} else if (time === 399) {
time = 359;
} else if (time === 299) {
time = 259;
} else if (time === 199) {
time = 159;
} else if (time === 99) {
time = 59;
}
if (time > 0) {
timeText.innerHTML = formatTime(time);
} else {
clearInterval(timer);
timeText.innerHTML = 'end';
}
}
function nextPage() {
clearInterval(timer);
sessionStorage.setItem('timerem', time);
window.open('02page2.html', "_self");
}
function loadTimer() {
var timeText = document.getElementById('timer');
if (sessionStorage.getItem('timerem') === null) {
timeText.innerHTML = 'ERROR';
} else {
time = sessionStorage.getItem('timerem');
timeText.innerHTML = formatTime(time)
timer = setInterval(countdown, 1000);
}
}
startTimer()
<span id="timer"></span>
Shorter version of your code without the page change and session storage - the session storage does not run in a stack snippet.
This is using actual time
const timeText = document.getElementById('timer');
let timer;
let time = 5*60*1000; // 5 minutes in millisecs
function startTimer() {
clearInterval(timer); // in case of restart
timer = setInterval(countdown, 1000);
}
function countdown() {
time-=1000;
const mmss = new Date(time).toISOString().substr(14, 5)
if (time > 0) {
timeText.textContent = mmss
} else {
clearInterval(timer);
timeText.innerHTML = 'end';
}
}
startTimer()
<span id="timer"></span>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var timer;
var time = 500;
function startTimer() {
timer = setInterval(countdown, 1000);
}
function countdown() {
time--;
var timeText = document.getElementById('timer');
if (time > 0) {
timeText.innerHTML = (time/100).toFixed(2).replace(".",":");
} else {
clearInterval(timer);
timeText.innerHTML = 'end';
}
}
function nextPage() {
clearInterval(timer);
sessionStorage.setItem('timerem', time);
window.open('02page2.html', "_self");
}
function loadTimer() {
var timeText = document.getElementById('timer');
if (sessionStorage.getItem('timerem') === null) {
timeText.innerHTML = 'ERROR';
} else {
time = sessionStorage.getItem('timerem');
timeText.innerHTML = (time/100).toFixed(2).replace(".",":");
timer = setInterval(countdown, 1000);
}
}
startTimer()
</script>
</head>
<body>
<span id="timer"></span>
</body>
</html>

timer stop & continue function in only one button in javascript

I want to build a timer controlled by one start button. when clicked, it will change innertext to "stop" and start the countdown, when clicked again, it will change to "continue" and pause the countdown. The problem is I don't know how to control the setinterval, because I declare it in dfferent if statment, I can't access the setinterval variable from other place.
Code:
const change = document.getElementById("change") -> countdown text part
const sb = document.getElementById("start") // button -> stop & pause
let stop = true;
let i; // setinterval variable
sb.addEventListener("click", () => {
let a = parseInt(change.innerText);
if(stop && a != 0) {
stop = false;
sb.innerText = "Stop";
i = setInterval(()=> {
a --;
change.innerText = a;
if(a == 0) {
stop = true;
alert("Time's Out!")
clearInterval(i);
sb.innerText = "Start";
}
}, 1000)
}
else if (!stop) {
stop = true;
sb.innerText = "continue";
// how to change this part to access setInterval variable i?
}
})
You should be able to call clearInterval within either section of your if-statement, since it is declared outside the scope of both. See here, a working example:
const s = document.querySelector('span');
const b = document.querySelector('button');
let interval = null;
b.onclick = () => {
// Start the interval
if (!interval) {
interval = setInterval(() => {
s.innerText = parseInt(s.innerText) - 1;
}, 1000);
b.innerText = "Pause";
} else {
clearInterval(interval);
interval = null;
b.innerText = "Resume";
}
}
<span id="countdown">100</span>
<button>Start</button>

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>

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