Add EXPIRATION message to JS countdown timer - javascript

I have following script:
document.getElementById("timer").innerHTML = 0 + ":" + 10;
function startTimer() {
var presentTime = document.getElementById("timer").innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond(timeArray[1] - 1);
if (s == 59) {
m = m - 1;
}
if (m < 0) {
return;
}
document.getElementById("timer").innerHTML = m + ":" + s;
console.log(m);
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {
sec = "0" + sec;
} // add zero in front of numbers < 10
if (sec < 0) {
sec = "59";
}
return sec;
}
<div class="sale_content">
СКИДКА АКТИВНА ЕЩЁ: <span id="timer"></span>
</div>
All works great, but when timer expires it just shows "0:00"
How can I add expiration message inside ?
Thank you!

You can add your message expiry message, inside the minute expiry if block if (m<0){} before the return statement. I added the solution to your code below for reference
<div class="sale_content">
СКИДКА АКТИВНА ЕЩЁ: <span id="timer"></span>
</div>
<script>
document.getElementById('timer').innerHTML =
0 + ":" + 3;
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m<0){
document.getElementById('timer').innerHTML = "Timer expired."
return
}
document.getElementById('timer').innerHTML =
m + ":" + s;
console.log(m)
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
if (sec < 0) {sec = "59"};
return sec;
}
startTimer();
</script>
</body>
</html>

the problem is that you want to console.log(m) which is just 0:00. I've changed a bit of your code so instead of m it logs n which is: n = m + ":" + s;
<div class="sale_content">
СКИДКА АКТИВНА ЕЩЁ: <span id="timer"></span>
</div>
<script>
document.getElementById('timer').innerHTML =
0 + ":" + 10;
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m<0){
return
}
document.getElementById('timer').innerHTML =
n = m + ":" + s;
console.log(n)
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
if (sec < 0) {sec = "59"};
return sec;
}
</script>
try it like this

var timeleft = 11;
var downloadTimer = setInterval(function(){
if(timeleft <= 0){
clearInterval(downloadTimer);
alert("Timer Expired!")
return;
}
document.getElementById("progressBar").value = timeleft - 1;
document.getElementById("timer").innerHTML = "0:"+(timeleft - 1);
timeleft -= 1;
}, 1000);
<div class="sale_content">
СКИДКА АКТИВНА ЕЩЁ: <span id="timer"></span>
</div>
<progress value="0" max="10" id="progressBar"></progress>

Related

implementing a stopwatch on a js game

I'm building a memory card game.
I want to show the time from the moment the user pressed on the first card till they win.
i dont understand how to make the stopwatch to continue counting while the player plays without it getting stuck or not refreshing the display enough.
HTML:
<h4 class="stopwatch">00:00:00</h4>
JavaScript:
while (TOTAL_COUPLES_COUNT !== flippedCouplesCount) {
sec++;
if (sec == 60) {
min = min + 1;
sec = 0;
}
if (min == 60) {
hr = hr + 1;
min = 0;
sec = 0;
}
elStopwatch.innerHTML = hr + ":" + min + ":" + sec;
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
setInterval(setTime, 1000);
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
<label id="minutes">00</label>:<label id="seconds">00</label>

JS interval not incrementing timer

The button I am listening in on and span element I want to
increment my timer in.
<p class="text2">art</p><br />
<p class="clocktext">
<span id="artSession">
<?php displayTime("art"); ?>
</span>
</p><br />
<button id="artBtn"> record </button><br />
<script type="text/javascript" src="includes/jquery.js"></script>
<script type="text/javascript" src="includes/jsfunctions.js"></script>
Here is my js functions file im calling from
// Beginning of tracker functionality
// variables to begin with
var interval;
var hours = 0;
var minutes = 0;
var seconds = 0;
var displayHrs = 0;
var displayMins = 0;
var displaySecs = 0;
var end, start, totalTime;
var timerStatus = false;
function sessionTimer() {
seconds = seconds + 1;
if(seconds >= 60 ) {
minutes++;
seconds = 0;
} else if ( minutes >= 60 ) {
hours++;
minutes = 0;
}
// logic to add leading 0
if( seconds < 10 ) {
displaySecs = '0' + seconds;
} else {
displaySecs = seconds;
} if( minutes < 10 ) {
displayMins = '0' + minutes;
} else {
displayMins = minutes;
} if( hours < 10 ) {
displayHrs = '0' + hours;
} else {
displayHrs = hours;
}
recordTime = displayHrs + ':' + displayMins + ':' + displaySecs;
document.getElementById('artSession').innerHTML = recordTime;
} // end of custom timer function
function buttonListening(catBtnId, catBtn, catSession, catSessionId, catagory) {
$(catBtnId).click(function() {
if(timerStatus == false) {
interval = setInterval(sessionTimer(), 1000);
document.getElementById(catBtn).innerHTML = 'stop';
timerStatus = true;
start = new Date();
}
else if (timerStatus == true) {
clearInterval(interval);
document.getElementById(catBtn).innerHTML = 'record';
end = new Date();
totalTime = end.getTime() - start.getTime();
timerStatus = false;
// reset timer values
hours = 0;
minutes = 0;
seconds = 0;
displayHrs = 0;
displayMins = 0;
displaySecs = 0;
// logic to add leading 0
if( seconds < 10 ) {
displaySecs = '0' + seconds;
} else {
displaySecs = seconds;
} if( minutes < 10 ){
displayMins = '0' + minutes;
} else {
displayMins = minutes;
} if( hours < 10 ){
displayHrs = '0' + hours;
} else {
displayHrs = hours;
}
//display formatted time in div
recordTime = displayHrs + ':' + displayMins + ':' + displaySecs;
document.getElementById(catSession).innerHTML = recordTime;
//#sign required !!include full path
$(catSessionId).load( 'includes/submit_time.php', {
postTimeCat: catagory ,
postTotalTime: totalTime
});
}
});
} // end of custom function storing btn event ---------------------------------------
buttonListening("#artBtn","artBtn","artSession","#artSession","art");
}); // end of js
Not quite sure where I'm going wrong. It was all working earlier today... GAHHH this project forsure has empowered me to start using github. Hope one of you guys can help me :C spent like all day smashing face off keyboard to get this thing to work. pet project almost done!
timeInterval = setInterval(sessionTimer(), 1000);
don't need parentheses '()' when passing function name in setInterval()
timeInterval = setInterval(sessionTimer, 1000);
hope this saves someone 4hrs

Javascript Timer project: why is clearInterval not working?

I am a beginner trying to learn JavaScript. My project is to make a stopwatch with stop, reset, and go.
For some reason, I can't figure out how to get clearInterval() to stop the goFunction. Any help would be appreciated.
var min = 00
var sec = 00
var ms = 00
function goFunction() {
var swTimer = setInterval(addTime, 10)
function addTime() {
if (ms < 99) {
ms++
} else {
sec += 1
ms = 0
}
if (sec > 59) {
min += 1
sec = 0
}
msShow = (ms < 10) ? "0" + ms : ms
secShow = (sec < 10) ? "0" + sec : sec
minShow = (min < 10) ? "0" + min : min
document.getElementById("numbers").innerHTML = minShow + ":" + secShow + ":" + msShow
}
}
function stopFunction() {
document.getElementById("numbers").style.color = "red"
clearInterval(swTimer);
}
<div class="controls">
<button onclick="goFunction()" class="button button1">GO</button>
<button onclick="resetFunction()" class="button button2">RESET</button>
<button onclick="stopFunction()" class="button button3">STOP</button>
<div class="display" id="numbers">00:00:00</div>
</div>
Declare your swTimer outside goFunction
<div class = "controls">
<button onclick="goFunction()" class="button button1">GO</button>
<button onclick="resetFunction()" class="button button2">RESET</button>
<button onclick="stopFunction()" class="button button3">STOP</button>
<div class="display" id = "numbers">00:00:00</div>
</div>
<script>
var min = 00
var sec = 00
var ms = 00
var swTimer
function goFunction() {
swTimer= setInterval(addTime, 10)
function addTime() {
if (ms < 99) {
ms++
} else {
sec+=1
ms = 0
}
if (sec >59 ) {
min+=1
sec=0
}
msShow = (ms<10) ? "0" + ms : ms
secShow = (sec<10) ? "0" + sec : sec
minShow = (min<10) ? "0" + min : min
document.getElementById("numbers").innerHTML = minShow + ":" + secShow + ":" + msShow
}
}
function stopFunction() {
document.getElementById("numbers").style.color = "red"
clearInterval(swTimer);
}
</script>
Because swTimer is not global = it's declared and scoped at goFunction and is not defined/accessible in stopFunction.
Set it outside the functions (my opinion: before - where min, sec and ms are declared).
The problem is that swTimer is inside the goFunction block, declare swTimer as a global variable.
var min = 0;
var sec = 0;
var ms = 0;
function addTime() {
if (ms < 99) {
ms++
} else {
sec+=1
ms = 0
}
if (sec >59 ) {
min+=1
sec=0
}
msShow = (ms<10) ? "0" + ms : ms
secShow = (sec<10) ? "0" + sec : sec
minShow = (min<10) ? "0" + min : min
document.getElementById("numbers").textContent = minShow + ":" + secShow + ":" + msShow
}
var swTimer = setInterval(addTime, 1000);
function stopFunction() {
document.getElementById("numbers").style.color = "red"
clearInterval(swTimer);
}
window.onload = addTime();
<p id="numbers"></p>
<button onclick="stopFunction()">Go!</button>
The interval won't get cleared because it is locally scoped. You defined in a function which means it cannot be globally accessed in another function a solution would be
var min = 00
var sec = 00
var ms = 00
function addTime() {
if (ms < 99) {
ms++
} else {
sec+=1
ms = 0
}
if (sec >59 ) {
min+=1
sec=0
}
msShow = (ms<10) ? "0" + ms : ms
secShow = (sec<10) ? "0" + sec : sec
minShow = (min<10) ? "0" + min : min
document.getElementById("numbers").innerHTML = minShow + ":" + secShow + ":" + msShow
}
var swTimer
function goFunction() {
swTimer = setInterval(addTime, 10)
}
function stopFunction() {
document.getElementById("numbers").style.color = "red"
clearInterval(swTimer);
}
<div class = "controls">
<button onclick="goFunction()" class="button button1">GO</button>
<button onclick="resetFunction()" class="button button2">RESET</button>
<button onclick="stopFunction()" class="button button3">STOP</button>
<div class="display" id = "numbers">00:00:00</div>
</div>

How can i get the seconds to reset to 0 when they reach 60

Hi there I have a stopwatch embedded in my website, however I have a problem. When the seconds reach 60 therefore 1 minute they should reset to 00. However in this case while the minute will increase every 60 seconds the seconds will not reset to zero. Here is my code
<div id="output">00:00:00</div>
<button id="startPause" onclick="startPause()">Start</button>
<button onclick="reset()">Reset</button>
<script type="text/javascript">
var time = 0;
var running = 0;
function startPause() {
if (running == 0) {
running = 1;
increment();
document.getElementById('startPause').innerHTML = 'Pause';
} else {
running = 0;
document.getElementById('startPause').innerHTML = 'Resume';
}
}
function reset() {
running = 0;
time = 0;
document.getElementById('output').innerHTML = '00:00:00';
document.getElementById('startPause').innerHTML = 'Start';
}
function increment() {
if (running == 1) {
setTimeout(function() {
time++;
var mins = Math.floor(time / 10 / 60);
if (mins <= 9) {
mins = '0' + mins;
}
var secs = Math.floor(time / 10);
if (secs <= 9) {
secs = '0' + secs;
}
var tenths = Math.floor(time % 10);
if (tenths <= 9) {
tenths = '0' + tenths;
}
document.getElementById('output').innerHTML =
mins + ':' + secs + ':' + tenths;
increment();
}, 100);
}
}
</script>
Any help much appreciated
You can use that code
<div id="output">00:00:00</div>
<button id="startPause" onclick="startPause()">Start</button>
<button onclick="reset()">Reset</button>
<script type="text/javascript">
var time = 0;
var running = 0;
function startPause() {
if (running == 0) {
running = 1;
increment();
document.getElementById('startPause').innerHTML = 'Pause';
} else {
running = 0;
document.getElementById('startPause').innerHTML = 'Resume';
}
}
function reset() {
running = 0;
time = 0;
document.getElementById('output').innerHTML = '00:00:00';
document.getElementById('startPause').innerHTML = 'Start';
}
function increment() {
if (running == 1) {
setTimeout(function() {
time++;
var mins = Math.floor(time / 10 / 60);
if (mins <= 9) {
mins = '0' + mins;
}
var secs = Math.floor(time / 10);
if(secs >= 60)
{
secs = secs - ( mins * 60 );
}
if ((secs).toString().length === 1) {
secs = '0' + secs;
}
var tenths = Math.floor(time % 10);
if ((tenths).toString().length === 1) {
tenths = '0' + tenths;
}
document.getElementById('output').innerHTML =
mins + ':' + secs + ':' + tenths;
increment();
}, 100);
}
}
</script>
Just include a modulo by 60 to line number 36 to properly reset seconds to 0 (line commented to highlight):
<div id="output">00:00:00</div>
<button id="startPause" onclick="startPause()">Start</button>
<button onclick="reset()">Reset</button>
<script type="text/javascript">
var time = 0;
var running = 0;
function startPause() {
if (running == 0) {
running = 1;
increment();
document.getElementById('startPause').innerHTML = 'Pause';
} else {
running = 0;
document.getElementById('startPause').innerHTML = 'Resume';
}
}
function reset() {
running = 0;
time = 0;
document.getElementById('output').innerHTML = '00:00:00';
document.getElementById('startPause').innerHTML = 'Start';
}
function increment() {
if (running == 1) {
setTimeout(function() {
time++;
var mins = Math.floor(time / 10 / 60);
if (mins <= 9) {
mins = '0' + mins;
}
var secs = Math.floor(time / 10) % 60; // <-- see here for change
if (secs <= 9) {
secs = '0' + secs;
}
var tenths = Math.floor(time % 10);
if (tenths <= 9) {
tenths = '0' + tenths;
}
document.getElementById('output').innerHTML =
mins + ':' + secs + ':' + tenths;
increment();
}, 100);
}
}
</script>

How to Run the time that the timezone is Denmark Copenhagen

I found the code which is can run my stopwatch. but iwant to follow denmark country timezone to run my code. how to d
<script type="text/javascript">
ElapsedTimeLogger = function(dateElementId, elapsedElementId, hiden, interval) {
var container = $(elapsedElementId);
var time = parseDate($(dateElementId).val());
var interval = interval;
var timer;
function parseDate(dateString) {
var date = new Date(dateString);
return date.getTime();
}
function update() {
var systemTime = new Date().getTime();
elapsedTime = systemTime - time;
container.html(prettyPrintTime(Math.floor(elapsedTime / 1000)));
$(hiden).val(prettyPrintTime(Math.floor(elapsedTime / 1000)));
}
function prettyPrintTime(numSeconds) {
var hours = Math.floor(numSeconds / 3600);
var minutes = Math.floor((numSeconds - (hours * 3600)) / 60);
var seconds = numSeconds - (hours * 3600) - (minutes * 60);
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
var time = hours + ":" + minutes + ":" + seconds;
return time;
}
this.start = function() {
timer = setInterval(function() {update()}, interval * 1000);
}
this.stop = function() {
clearTimeout(timer);
}
}
$(document).ready(function () {
var timeLogger = new ElapsedTimeLogger("#date", "#elapsed","#stoppedid", 1);
timeLogger.start();
$("#confirm").click(function() { //Stop timer upon clicking the Confirm Button
timeLogger.stop();
});
});
</script>
Thank you in advance.
I cant post another question thats why i need to edit may other questions
remove disabled property of input[name=stwa] and add readonly property for there
Use navigator.cookie to save time on javascript
Here is your solutions
if(localStorage.getItem("sec"))
{
var sec = localStorage.getItem("sec");
var min = localStorage.getItem("min");
var hour = localStorage.getItem("hour");
stopwatch("Start");
}else{
var sec = 0;
var min = 0;
var hour = 0;
}
function stopwatch(text) {
sec++;
if (sec == 60) {
sec = 0;
min = min + 1; }
else {
min = min; }
if (min == 60) {
min = 0;
hour += 1; }
localStorage.setItem("sec", sec);
localStorage.setItem("min", min);
localStorage.setItem("hour", hour);
if (sec<=9) { sec = "0" + sec; }
document.clock.stwa.value = ((hour<=9) ? "0"+hour : hour) + " : " + ((min<=9) ? "0" + min : min) + " : " + sec;
if (text == "Start") { document.clock.theButton.value = "Start "; }
if (text == "Stop ") { document.clock.theButton.value = "Stop"; }
if (document.clock.theButton.value == "Start") {
window.clearTimeout(SD);
return true; }
SD=window.setTimeout("stopwatch();", 1000);
}
function stop() {
x.stop();
document.getElementById('counter').value = formatTime(x.time());
clearInterval(clocktimer);
localStorage.clear();
}
<form name="clock" action="save_time_log.php" method="post">
<div class="form-group">
<input type="text" class="form-control time_tracker" disabled name="stwa" placeholder="00:00:00">
</div>
<input type="button" name="theButton" onClick="stopwatch(this.value);" class="btn btn-block btn-default btn-flat" value="Start" />
<input type="submit" name="stops" value="Stop" onClick="stop();" class="btn btn-block btn-default btn-flat"/>
</form>

Categories