How to start a eggtimer after clearInterval()? - javascript

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>

Related

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>

Create a simple 2 minutes countdown

I want to make a count of 2 minutes, but I want to give you click to the button "Start", so far, and managed to make it work, but I have an error in the minutes does not run as well back but that appears NaN:seconds.
I show them the code that i am working on.
var timeoutHandle;
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins-1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
timeoutHandle=setTimeout(tick, 1000);
} else {
if(mins > 1){
// countdown(mins-1); never reach “00″ issue solved:Contributed by Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
document.getElementById("timer").innerHTML = "Finished"
}
}
tick();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="tempo-completo">
<div id="timer">2:00</div>
<button onclick="countdown()">INICIAR</button>
</div>
You are not passing in the number of minutes to the countdown() function.
var timeoutHandle;
function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins-1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if( seconds > 0 ) {
timeoutHandle=setTimeout(tick, 1000);
} else {
if(mins > 1){
// countdown(mins-1); never reach “00″ issue solved:Contributed by Victor Streithorst
setTimeout(function () { countdown(mins - 1); }, 1000);
}
document.getElementById("timer").innerHTML = "Finished"
}
}
tick();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="tempo-completo">
<div id="timer">2:00</div>
<button onclick="countdown(2)">INICIAR</button>
</div>
Jeremy Harris' answer is working perfectly fine, but i would like to propose another one.
Don't use setTimeout to make an interval function, use setInterval. Using setTimeout with a recursive loop is overall less precise
With that in mind i've tweek your code to incorporate this idea.
var timeoutHandle;
function countdown(minutes) {
var seconds = 60;
var mins = minutes
var counter = document.getElementById("timer");
var current_minutes = mins-1
// we create an interval variable to clear it later
// we also use an arrow function to have access to variable
// outside of the current function's scope.
let interval = setInterval(() => {
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
// our seconds have run out
if(seconds <= 0) {
// our minutes have run out
if(current_minutes <= 0) {
// we display the finished message and clear the interval so it stops.
counter.innerHTML = "Finished"
clearInterval(interval);
} else {
// otherwise, we decrement the number of minutes and change the seconds back to 60.
current_minutes--;
seconds = 60;
}
}
// we set our interval to a second.
}, 1000);
}
<div class="tempo-completo">
<div id="timer">2:00</div>
<button onclick="countdown(2)">INICIAR</button>
</div>

stopwatch not functioning properly

I'm just starting with javascript, I've been trying to make a simple stopwatch, I found a couple of ways to do it , then I came across this function ... the code doesn't work as a stopwatch unless we return a function , can somebody help me understand why????
for (var i = 1; i <= 5; i++) {
var tick = function(i) {
return ()=>{console.log(i);}
};
setTimeout(tick(i), 500 * i);
}
You should use setInterval and clearInterval for your case.
var i = 10;
var tick = function(i) {
return ()=>{
console.log(i--);
if(i == 0) clearInterval(timer);
}
};
var timer = setInterval(tick(i), 500);
If you want to have stopwatch, you can clearInterval in stop button click event
function stop(){
clearInterval(timer);
}
Update:
I combined Start and Stop in only one button using addEventListener and removeEventListener
var i = 1;
var timer;
var tick = function(i) {
return ()=>{
console.clear();
console.log(i++);
//if(i == 0) clearInterval(timer);
}
};
function start(){
document.getElementById("start").disabled = true;
document.getElementById("stop").disabled = false;
timer = setInterval(tick(i), 500);
}
function stop(){
clearInterval(timer);
document.getElementById("stop").disabled = true;
document.getElementById("start").disabled = false;
}
(function() {
document.getElementById("start2").addEventListener("click", start2);
})();
function start2(){
timer = setInterval(tick(i), 500);
document.getElementById("start2").innerHTML = "Stop";
document.getElementById("start2").removeEventListener("click", start2);
document.getElementById("start2").addEventListener("click", stop2);
}
function stop2(){
clearInterval(timer);
document.getElementById("start2").innerHTML = "Start";
document.getElementById("start2").removeEventListener("click", stop2);
document.getElementById("start2").addEventListener("click", start2);
}
<button id="start" onclick="start()">Start</button>
<button id="stop" onclick="stop()">Stop</button>
<h2>Combine Start and Stop</h2>
<button id="start2" >Start</button>
Because setTimeout first parameter has to be a function.
Your code works because it immediately executes the tick(i) function, which returns a function and that one is used 500ms later as callback.
below code will help you
<h1><time>00:00:00</time></h1>
<button id="start">start</button>
<button id="stop">stop</button>
<button id="clear">clear</button>
</pre>
<script>
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
start.onclick = function(){
timer();
start.disabled=true;
}
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
start.disabled=false;
}
/* Clear button */
clear.onclick = function() {
h1.textContent = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
</script>

Delay in timer when tab is inactive or browser minimised

I have the following code to show a timer for an online quiz application.On completion , I need to redirect to another page via ajax.
The code works for me,but I found that the timer delays when we shift tabs or minimise the browser.
var mins = 5;
var secs = 0; // Seconds (In addition to min) test time
var timerDisplay = $(document).find('#timerspan');
//Globals:
var timeExpired = false;
// Test time in seconds
var totalTime = secs + (mins * 60);
var countDown = function (callback) {
var interval;
interval = setInterval(function () {
if (secs === 0) {
if (mins === 0) {
timerDisplay.text('0:00');
clearInterval(interval);
callback();
return;
} else {
mins--;
secs = 60;
}
}
var minute_text;
if (mins > 0) {
minute_text = mins;
} else {
minute_text = '0';
}
var second_text = secs < 10 ? ('0' + secs) : secs;
timerDisplay.text(minute_text + ':' + second_text);
secs--;
}, 1000, timeUp);
};
// When time elapses: submit form
var timeUp = function () {
alert("Time's Up!");
timeExpired = true;
var completed=1;
$.ajax({
type:"POST",
url:"success.php",
data:{'userID':<?php echo $_SESSION['userID'];?>},
success: function (hasil) {
$('.response_div').html(hasil);
}
});
};
// Start the clock
countDown(timeUp);

Game Timer Javascript

I'm creating a countdown timer. If seconds is equal to zero I have set 2 secs to var seconds. Please help. I need to stop the program from looping after getting the 2 seconds
var isWaiting = false;
var isRunning = false;
var seconds = 10;
function GameTimer(){
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if(remainingSeconds < 10){
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('waiting_time').innerHTML = minutes + ":" + remainingSeconds;
if(seconds == 0){
isRunning = true;
seconds += 2; //I need to stop the program from looping after getting the 2 seconds
}else{
isWaiting = true;
seconds--;
}
}
var countdownTimer = setInterval(GameTimer(),1000);
Here is your fixed code:
var isWaiting = false;
var isRunning = false;
var seconds = 10;
var countdownTimer;
var finalCountdown = false;
function GameTimer() {
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('waiting_time').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
isRunning = true;
seconds += 2;
if (finalCountdown) {
clearInterval(countdownTimer); // Clear the interval to stop the loop
} else {
finalCountdown = true; // This will allow the 2 additional seconds only once.
}
} else {
isWaiting = true;
seconds--;
}
}
countdownTimer = setInterval(GameTimer, 1000); // Pass function reference, don't invoke it.
WORKING DEMO: http://jsfiddle.net/nEjL4/1/
since i couldn't understand the code that's up in the question i wrote down my own timer. So take a look if it works out for you.
http://jsfiddle.net/9sEGz/
var m=getId('m'), s=getId('s'), btn=getId('btn'), status=getId('status'), inc =getId('inc') , dec =getId('dec'), interval=null, time=0, min=0;
btn.onclick = startCounter;
inc.onclick = incTime;
dec.onclick = decTime;
function startCounter() {
if (time<=0) {
status.textContent='Increase the timer first!';
time=0;
return;
}
status.textContent='Counting!';
btn.textContent = 'Stop';
btn.onclick = stopCounter;
interval = setInterval(function(){
time--;
if (time<=0) {
stopCounter();
status.textContent='Time\'s Up';
}
setTime();
},200);
}
function stopCounter() {
btn.textContent = 'Start';
btn.onclick = startCounter;
status.textContent='Stopped!';
if (interval) clearInterval(interval);
}
function incTime(){
time++;
setTime();
}
function decTime(){
time--;
setTime();
}
function setTime() {
min= time/60;
if (time<10) s.textContent= '0'+Math.floor(time%60);
else s.textContent= Math.floor(time%60);
if (min<0) m.textContent= '00';
else if (min<10) m.textContent= '0'+Math.floor(min);
else m.textContent= Math.floor(min);
}
function getId(x) {
return document.getElementById(x);
}

Categories