Making a timer with code that can easily be reset - javascript

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>

Related

I created a stopwatch using JavaScript, and I'm trying to start/stop the timer by space key, but it doesn't stop but always became more faster

I created a stopwatch using JavaScript, and I'm trying to start/stop the timer by space key, but it doesn't stop but always became more faster.
'''
var timer_start = "S";
var time;
document.body.onkeyup = function (e) {
if (e.keyCode == 32) {
time = setInterval(timer, 10);
if (timer_start == "S") {
timer_start = "F";
} else if (timer_start == "F") {
clearInterval(time);
timer_start = "S";
}
}
};
,,,
Once the spacebar is pressed, you are starting the timer again regardless of the current value of timer_start. You need to move this to be inside the if statement. I'd also recommend using a Boolean instead of the string "S" and "F".
Here is my proposed rewrite of your code:
var timer_start = true;
var time;
document.body.onkeyup = function (e) {
if (e.keyCode == 32) {
if (timer_start) {
time = setInterval(timer, 10);
timer_start = false;
} else {
clearInterval(time);
timer_start = true;
}
}
};
You could also shorten it a bit by doing this if you wanted
var timer_start = true;
var time;
document.body.onkeyup = function (e) {
if (e.keyCode == 32) {
if (timer_start) {
time = setInterval(timer, 10);
} else {
clearInterval(time);
}
timer_start = !timer_start
}
};
You set the interval regardless of the timer_start state, so you keep piling up new intervals and remove only half of them. You should set the interval only in the timer_start == "S" branch.

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>

Counting up and down to specified number in order in Javascript

I am trying to get this script to count up to a specified number and back down to a specified number as follows: 19200, 38400, 57600, 76800, 96000, 76800, 57600, 38400, 19200 — repeatedly. So far this is what I have but I cannot seem to make it count down in the order above, it restarts from 19200 again.
$(function() {
var seconds = 19200;
var timerId = setInterval(function() {
seconds = seconds + 19200;
$("#counter").text(seconds);
if (seconds > "76800") {
clearInterval(seconds);
seconds = seconds - "19200";
}
}, 500);
});
A little issue with the logic, the condition
if (seconds > "76800") {
would always try to keep the seconds above 76800.
Rather you would want a flag to track the direction of the count. Check out below:
UPDATED:
Working demo at
JSFiddle
$(function () {
var increment = 19200;
var seconds = increment;
var countUp = true;
var timerId = setInterval(function () {
$("#counter").text(seconds);
if (countUp) {
seconds += increment;
} else {
seconds -= increment;
}
if (countUp && seconds > increment*4) {
countUp = false;
} else if (!countUp && seconds <= increment) {
countUp = true;
}
}, 500);
});
Check the below function
$(function() {
var seconds = 19200;
action = 'add';
var timerId = setInterval(function() {
$("#counter").text(seconds);
if (seconds == 96000) {
action = 'remove';
} else if (seconds == 19200) {
action = 'add'
}
if (action == 'add')
seconds += 19200;
else if (action == 'remove')
seconds -= 19200;
}, 500);
});
I think this is a little more elegant
var increment = 19200,
seconds = increment;
var timer = setInterval(function() {
console.log(seconds);
seconds += increment;
if (seconds > 76800 || seconds < 19200) {
increment *= -1;
}
}, 500);
jsfiddle

Time to start only after button click

http://jsfiddle.net/Bwdfw/98/
is there a way to start timer only after a button is clicked in the given jsfiddle link
http://jsfiddle.net/Bwdfw/98/
var seconds=0;
var Score=0;
var index=0;
countdown(60);
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
Have a function inside the click handler and a variable which states if the function has started or not.
Also you can club the click events inside a single handler and the index can be stored as part of the data-* attributes which reduces duplicated code.
Javascript
//Timer //
var seconds = 0,
Score = 0,
index = 0,
timerStarted = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if (seconds > 60 && Score < 30) {
alert("Not enough Score");
}
if (seconds > 0) {
setTimeout(tick, 1000);
}
}
$("#one, #two, #three").click(function () {
if(!timerStarted) {
countdown(60);
timerStarted = true;
}
var dataIndex = $(this).data('index');
if (index == dataIndex) {
Score++;
if(dataIndex == 2) {
index = 0;
} else {
index++;
}
}
$("#score").html("Score: " + Score);
});
HTML
<div id="timer"></div>
<div id="score">Score: 0</div>
<button id="one" type="button" data-index="0">Button1</button>
<button id="two" type="button" data-index="2">Button2</button>
<button id="three" type="button" data-index="1">Button3</button>
Check Fiddle
var seconds=0;
var Score=0;
var index=0;
var started = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
$("button").click(function(){
if(!started){
started = true;
countdown(60);
}
});
You could generate custom event after click
$(window).trigger('clicked');
$(window).on('clicked', function() {
setTimeout(tick, 1000);
});
http://jsfiddle.net/Bwdfw/100/
Just remember to check if the countdown has not started yet.
$("button").click(function(){
});
This will add a handler to all the buttons in your DOM, then just check the status of the countdown.
Check this fiddle:
http://jsfiddle.net/eddiarnoldo/Bwdfw/102/

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