Java script keypress event - javascript

I am trying to use the keypress event in my project to start a countdown timer but I keep getting a decrement for every keystroke.
I don't know what's wrong with my js code.
var timeleft = 60;
var timer = document.getElementById('timer');
var input = document.getElementById("input");
var timerId = setInterval(countdown);
input.addEventListener("keypress", countdown, 1000);
function countdown(event) {
if (event.key !==undefined){
if (timeleft == -1) {
clearTimeout(timerId);
}
else {
timer.innerHTML = timeleft;
timeleft--;
}
}
};

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.

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)

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>

How to start a eggtimer after clearInterval()?

A have an eggtimer which can be stopped after clicking on the button "stop". What I want is making this timer working again (from the point where it stopped) after clicking "cancel" in a confirm box. Any sugestions? Thanks for help :)
<!DOCTYPE html>
<html>
<body onload="timer();">
<button onclick="exit();">stop</button>
<p id="seconds">30</p>
<script type="text/javascript">
var clock;
function timer () {
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(30 - (new Date().getTime() - start) / 1000);
if (seconds >= 0)
document.getElementById('seconds').innerHTML = seconds;
else
clearInterval(clock);
if (seconds==0) {window.location.href="something.com";
return;
}
}, 1000);
}
function exit(){
clearInterval(clock);
var result = confirm("Are you leaving?");
if (result == true) {
window.location.href="somewhere.com";
}
else {
timer();} // <-- ????
}
</script>
</body>
</html>
You can create a variable that holds in what seconds you are ;
var sec = seconds;
Change your function timer with the timer you want to start as a paramerter
function timer (time)
var clock;
var sec;
function timer (time) {
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(time - (new Date().getTime() - start) / 1000);
sec = seconds;
if (seconds >= 0){
document.getElementById('seconds').innerHTML = seconds;
}
else{
clearInterval(clock);
}
if (seconds==0){
window.location.href="something.com";
return;
}
}, 1000);
}
function exit(){
clearInterval(clock);
var result = confirm("Are you leaving?");
if (result == true) {
window.location.href="somewhere.com";
}
else {
console.log(sec);
timer(sec);} // <-- ????
}
<body onload="timer(30);">
<button onclick="exit();">stop</button>
<p id="seconds">30</p>
</body>
Here's a working example.
I moved the seconds variable outside the function so it persists and can be used to re-start the timer.
Also, I added an argument to the timer() function so the count down amount can be changed.
Note that the granularity is at the second level, so the actual count down time might eventually be longer than 30 seconds, but I believe it is acceptable in this use case.
var clock;
var seconds;
function timer(wait) {
var start = new Date().getTime();
clock = setInterval(function() {
seconds = Math.round(wait - (new Date().getTime() - start) / 1000);
if (seconds >= 0)
document.getElementById('seconds').innerHTML = seconds;
else
clearInterval(clock);
if (seconds == 0) {
window.location.href = "something.com";
return;
}
}, 1000);
}
function exit() {
clearInterval(clock);
var result = confirm("Are you leaving?");
if (result == true) {
window.location.href = "somewhere.com";
} else {
timer(seconds);
} // <-- ????
}
timer(30);
<button onclick="exit();">stop</button>
<p id="seconds">30</p>

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>

Categories