Trying to format timer like 5:00 instead of 500 - javascript

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>

Related

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>

Stop the coundown timer if the user wins

I added a timer to my memory game, and i want to stop it when the user matches all the 8 cards.
window.onload = function() {
var timeoutHandle;
function countdown(minutes, seconds) {
function tick() {
var timecounter = document.getElementById("timer");
timecounter.innerHTML = minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
seconds--;
if (seconds >= 0) {
timeoutHandle = setTimeout(tick, 1000);
} else {
if (minutes >= 1) {
setTimeout(function () {
countdown(minutes - 1, 59);
}, 1000);
}
}
if (seconds==0 && minutes ==0){
alert("Game over");
//reset();
}
}
tick();
}
countdown(1, 00); }
the above is the countdown timer function
if (matches == 8) {
document.getElementById("finalMove").innerHTML = moves;
clearTimeout(timeoutHandle);
showWinScreen();
}
can you suggest a solution for this.

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>

My JQuery count down is not working perfectly,

I want to make a jQuery timer count down. It should have days, day, month, hours, seconds. I used this below code, but it is not working. When the browser is refreshed, the counter is restarting. Please help me to correct this code.
This is the jsFiddle
https://jsfiddle.net/saifudazzlings/LfLdo381/
The js code:
var sec = 60;
var min = 100;
var hr = 24;
var updateTimer = function() {
var timer = localStorage.getItem('timer') || 0;
var timermin = localStorage.getItem('timermin') || 0;
var timerhr = localStorage.getItem('timerhr') || 0;
$("div#timermin").html(timermin);
$("div#timerhr").html(timerhr);
if (timer === 0) {
$("div#timer").html("00");
} else if (timer <= 1) {
timer--;
timermin--;
localStorage.setItem('timermin', timermin);
$("div#timermin").html(timermin);
if (timermin < 1) {
if (timerhr == 0) {
localStorage.removeItem('timermin', timermin);
$("div#timermin").html("00");
localStorage.removeItem('timer', timer);
$("div#timer").html("00");
localStorage.removeItem('timerhr', timerhr);
$("div#timerhr").html("00");
} else {
timerhr--;
localStorage.setItem('timerhr', timerhr);
$("div#timerhr").html(timerhr);
localStorage.setItem('timermin', min);
$("div#timermin").html(timermin);
}
//timerhr--;
//localStorage.setItem('timerhr', timerhr);
//$("div#timerhr").html(timerhr);
//localStorage.setItem('timermin', min);
//$("div#timermin").html(timermin);
}
localStorage.setItem('timer', sec);
$("div#timer").html(timer);
} else {
timer--;
localStorage.setItem('timer', timer);
$("div#timer").html(timer);
if (timermin == 0) {
localStorage.removeItem('timer', timer);
$("div#timer").html("00");
$("div#countermessage").html("00");
}
}
};
$(function() {
$("#start").click(function() {
localStorage.setItem('timer', sec);
});
$("#start2").click(function() {
localStorage.setItem('timermin', min);
localStorage.setItem('timerhr', hr);
});
setInterval(updateTimer, 1000);
$(window).load(function() {
localStorage.setItem('timer', sec);
localStorage.setItem('timermin', min);
localStorage.setItem('timerhr', hr);
});
});

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