My JQuery count down is not working perfectly, - javascript

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);
});
});

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>

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.

javascript in the table does not work when it is responsive

jQuery.noConflict();
(function($) {
$(function() {
function toTimeString(seconds) {
return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}
function startTimer() {
var dataStartElem = jQuery(this);
var dataStart = dataStartElem.attr('data-start');
if (dataStart == 'false') {
dataStartElem.attr('data-start', 'true');
var nextElem = dataStartElem.parent('td').next('.count');
var duration = dataStartElem.attr('data-value');
var a = duration.split(':');
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
setInterval(function() {
seconds--;
if (seconds >= 0) {
nextElem.html(toTimeString(seconds));
dataStartElem.attr('data-start', 'false');
}
if (seconds === 0) {
alert('time out');
clearInterval(seconds);
}
}, 1000);
}
}
jQuery('.timer').on('click', startTimer);
$('table').stacktable();
});
})(jQuery);
fiddle demo https://jsfiddle.net/arra6j6h/6/
javascript timer in the table does not work and time does not appear when responsive, but all normal when not responsive

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

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