timer stop & continue function in only one button in javascript - 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>

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 doesn't works and increases interval speed

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>

Count down timer on multiple pages

I have a timer on the home page. When user makes any action, such as mouse move, the timer will be reseted. When the timer count down to 05:00, system will pop-up a alert to reset timer by clicking "OK". If no action within 5 min and timer count down to 00:00, user forced to log out.
My problem is this timer only works within one page, if I have two pages opened, the timer only reset on focused page. I'll still be logged out due to the unfocused page.
Can anyone help me on this? Thanks so much!
<script type="text/javascript">
var flag = false;
startTimer();
function startTimer() {
var presentTime = $("#Status").text().toString();
var timeArray = presentTime.split(":");
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59) {
m=m-1;
if(m < 10) {
m = "0" + m;
}
}
if (m==05 && s==00) {
flag = true;
BootstrapDialog.alert("You have 5 minutes remaining in your session. Click \"OK\" to extend the session.", function() {
flag = false;
resetTimer();
});
}
if(!flag) {
//Reset timer upon user action
document.onload = resetTimer;
document.onmousemove = resetTimer;
document.onmousedown = resetTimer;
document.ontouchstart = resetTimer;
document.onclick = resetTimer;
document.onscroll = resetTimer;
document.onkeydown = resetTimer;
}
else {
document.onload = null;
document.onmousemove = null;
document.onmousedown = null;
document.ontouchstart = null;
document.onclick = null;
document.onscroll = null;
document.onkeydown = null;
}
if (m==0 && s==00) {
window.location.replace("/Logout");
};
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec};
if (sec < 0) {sec = "59"};
return sec;
}
function resetTimer() {
$("#Status").html("30:00");
}
</script>
<div> Your session has <h5 id="Status">30:00</h5> remaining. </div>
your problem is that you want to control two pages by 1 script,but variables in each page is independent.
if you solve this problem you could control your page.
you can get the variable m and s from cookie or localstorage. varibales in cookie and localstorage can be visit in different page if the these pages are in the same root.
try it,just replace the variables.get && set it from cookie or localstorage

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>

Javascript - Check if key was pressed twice within 5 secs

I want to check if Enter key was pressed twice within 5 secs and perform some action.
How can I check if the key was pressed once or twice within a given time and perform different actions.
Here is my code:
<h1 id="log">0</h1>
<br/>
<span id="enteredTime">0</span>
<script>
$(document).keypress(function(e) {
if(e.which == 13){
var element = $("#log");
var timeDifference = 0;
//Log the timestamp after pressing Enter
$("#enteredTime").text(new Date().getTime());
//Check if enter was pressed earlier
if ($("#enteredTime").text() !== "0") {
var now = new Date().getTime();
var previous = $("#enteredTime").text();
difference = now - previous;
}
//Check if enter was pressed only once within 5 secs or more
if(){
$("#log").text("Once");
$("#enteredTime").text("0");
//Check if enter was pressed twice in 5 secs
}else{
$("#log").text("Twice in less than 5 secs");
$("#enteredTime").text("0");
}
}
});
</script>
http://jsfiddle.net/Rjr4g/
Thanks!
something like
var start=0;
$(document).keyup(function(e) {
if(e.keyCode == 13) {
elapsed = new Date().getTime();
if(elapsed-start<=5000){
//do something;
}
else{
//do something else;
}
start=elapsed;
}
});
Try a timer based solution like
var flag = false,
timer;
$(document).keypress(function (e) {
var element = $("#log");
var timeDifference = 0;
if (e.which == 13) {
if (flag) {
console.log('second');
clearTimeout(timer);
flag = false;
} else {
console.log('first');
flag = true;
timer = setTimeout(function () {
flag = false;
console.log('timeout')
}, 5000);
}
//Log the timestamp after pressing Enter
$("#enteredTime").text(new Date().getTime());
if ($("#enteredTime").text() !== "0") {
var now = new Date().getTime();
var previous = $("#enteredTime").text();
difference = now - previous;
}
}
});
Demo: Fiddle
Bacon.js seems like a good tool to express this.
$(document).asEventStream('keypress')
.filter(function (x) {
return x.keyCode == 13;
})
.map(function () {
return new Date().getTime();
})
.slidingWindow(2, 1)
.map(function (x) {
return (x.length == 1 || x[1] - x[0] > 5000) ? 1 : 2;
})
.onValue(function (x) {
$("#log").text(x == 1 ? "Once" : "Twice in less than 5 secs");
});
(fiddle)
here is my solutions, please check it if match your idea :)
(function($){
var element = $("#log");
var timeDifference = 0;
var count = 0;
$(document).keypress(function(e) {
if(e.which === 13){
//do what you want when enterpress 1st time
/*blah blah */
//after done 1st click
count++;
if(count === 2) {
//do what you want when enterpress 2nd time in 5 seconds
/* blah blah */
//after done
clearTimeout(watcher);
count = 0;
return;
}
//setTimeout to reset count if more than 5 seconds.
var watcher = setTimeout( function() {
count = 0;
},5000);
}
});
}(jQuery)
Check your Updated Fiddle
var count = 0;
$(document).keypress(function(e) {
var element = $("#log");
var timeDifference = 0;
if(e.which == 13){
count++;
console.log('enter pressed'+count);
if(count == 1){
startTimer();
}
else{
checkCount();
}
//Log the timestamp after pressing Enter
$("#enteredTime").text(new Date().getTime());
if ($("#enteredTime").text() !== "0") {
var now = new Date().getTime();
var previous = $("#enteredTime").text();
difference = now - previous;
}
}
});
function startTimer(){
setTimeout(checkCount,5000);
}
function checkCount(){
if(count == 1){
$("#log").text("Once");
$("#enteredTime").text("0");
//Check if enter was pressed twice in 5 secs
}else{
$("#log").text("Twice in less than 5 secs");
$("#enteredTime").text("0");
}
}
startTimer() starts counting on first enter press. And checkCount() contains your condition after 5secs.
setTimeout() lets you attach an event which occurs after a specific timespan.

Categories