I'm trying to create a countdown timer in the format of 00:00:00 (minutes, seconds, and hundredths). Right the now the way I set up my countdown timer, is to make sure the user inputs in the format of 00:00:00 (which has to be). From there the countdown time should commence when they click the start button. I see that it does somewhat of a countdown, but I'm not sure what could be the problem with my implementation. The hundredths is not decrementing correctly for some reason. It should start of as 10:00:00 (10 mins) and go to 09:59:99.. 09:59:98, etc.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Countdown Timer</title>
<script type="text/javascript">
var running = 0;
var hundreds = 0;
function validTime() {
var setTime = document.getElementById("timeEntered").value;
var regex = /^\d{2}:\d{2}:\d{2}$/;
if (regex.test(setTime)) {
document.getElementById("timeAlert").innerHTML = "<span class='valid'>Valid</span>";
return (true);
} else {
document.getElementById("timeAlert").innerHTML = "<span class='error'>Invalid time entered. Please make sure it's in the format 00:00:00</span>";
return (false);
}
}
function correctTime(){
if (validTime()){
countdownTimer();
return true;
}else{
alert("Please correct your inputted time.");
return false;
}
}
function countdownTimer() {
var time = document.getElementById("timeEntered").value;
var a = time.split(":");
var timeToSeconds = (+a[0]) * 60 + (+a[1]) * 60 + (+a[2]);
if(parseInt(timeToSeconds) <= 600 ) {
startPause();
}else{
document.getElementById("output").innerHTML = "Sorry. Time range cannot exceed 10 mins.";
}
}
function startPause(){
var time = document.getElementById("timeEntered").value;
var a = time.split(":");
var timeToSeconds = (+a[0]) * 60 + (+a[1]) * 60 + (+a[2]);
if(running == 0){
running = 1;
decrement();
document.getElementById("startPause").innerHTML = "Start/Stop";
}else{
running = 0;
document.getElementById("startPause").innerHTML = "Resume";
}
}
var hundreds = 0;
function decrement(){
var time = document.getElementById("timeEntered").value;
var a = time.split(":");
var timeToSeconds = (+a[0]) * 60 + (+a[1]) * 60 + (+a[2]);
if(running == 1){
var mins = Math.round((timeToSeconds - 30)/60);
var secs = timeToSeconds % 60;
//var hundredths = timeToSeconds % 100;
if(mins < 10) {
mins = "0" + mins;
}
if(secs < 10) {
secs = "0" + secs;
}
document.getElementById("output").innerHTML = mins + ":" + secs + ":" + hundreds;
if (hundreds === 0){
if(timeToSeconds ===0){
clearInterval(countdownTimer);
document.getElementById("output").innerHTML = "Time's Up.";
}else{
timeToSeconds--;
hundreds = 100;
}
}else{
hundreds--;
}
var countdownTimer = setInterval('decrement()', 10)
}
}
</script>
</head>
<body>
<h1>Countdown Timer</h1>
<div id="mainCont">
<p>Please enter the desired time:
<input type="text" id="timeEntered" onblur="validTime();"> <span id="timeAlert"></span>
</p>
<p>
<button id="startPause" onclick="correctTime()">Start/Stop</button>
</p>
<div id="output">00:00:00</div>
</div>
</body>
</html>
I think #bholagabbar's code needs rewriting into hundreths of a second rather than in seconds.
function startTimer(duration, display) {
var timer = duration, minutes, seconds, dispms;
setInterval(function () {
dispms=parseInt(timer % 100,10);
seconds = parseInt(timer / 100, 10);
minutes = parseInt(seconds / 60, 10);
seconds = parseInt(seconds % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
dispms = dispms < 10 ? "0" + dispms : dispms;
display.textContent = minutes + ":" + seconds+":"+dispms;
if (--timer < 0) {
timer = duration;
}
}, 10); //hundreths of a second - 1000 would be 1 second
}
window.onload = function () {
var fiveMinutes = 60 * 5 * 100, //hundreths of second
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
I'm not sure if this is what you wanted but I have some working code for a timer that counts up to the given input (in seconds) which includes the 1/100th of a second. If you want to include ms as you mentioned, you will need 3 0's or ':000' for the display int the end. Here is the code. How will of course, have to mod it for your scenario but the timer is implemented perfe
function startTimer(duration, display) {
var timer = duration, minutes, seconds, dispms;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
dispms=parseInt((timer)%100,10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
dispms = dispms < 10 ? "0" + dispms : dispms;
display.textContent = minutes + ":" + seconds+":"+dispms;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
<body>
<div>Registration closes in <span id="time"></span> minutes!</div>
</body>
I think you will have to make changes only in the HTML part. Rest of the logic in my code is fine for a general timer. You will have to pass in the seconds as an argument, that is all
Related
var date = new Date;
var s = date.getSeconds();
var m = date.getMinutes();
var h = date.getHours();
setTimeout(function () {
$('#offer1').fadeOut('fast');
$('#remainingTime').fadeOut('fast');
}, 8640000);
function Timer(duration, display) {
var timer = duration, hours, minutes, seconds;
setInterval(function () {
hours = parseInt((timer / 3600) % 24, 10)
minutes = parseInt((timer / 60) % 60, 10)
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.text(parseInt(hours-h) + ":" + parseInt(minutes-m) + ":" + parseInt(seconds-s));
--timer;
}, 1000);
}
jQuery(function ($) {
var twentyFourHours = 24 * 60 * 60;
var display = $('#remainingTime');
Timer(twentyFourHours, display);
});
var i =$("remainingTime").textContent;
console.log(i);
<div class="ml-2">Time Remaining <span id="remainingTime">24:00:00</span></div>
<div id="offer1">asdf</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
Here, I've made a timer which says how much time is left for 24 Hours.
But it's showing Hours, Minutes and seconds in negative value for seconds after a minute and negative value for minutes after an Hour.
I need the both div elements ("offer1" and "remainingTime") should fade out after 24 hours timer.
By using the current Date and getTime() I should show the time remaining
Here is the JSFiddle Link https://jsfiddle.net/Manoj07/d28khLmf/2/...
Thanks for everyone who tried to help me. And here is the answer
https://jsfiddle.net/Manoj07/1fyb4xv9/1/
Hello this code works for me
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<div class="ml-2">Time Remaining <span id="remainingTime"></span></div>
<div id="offer1">asdf</div>
<script>
// this code set time to 24 hrs
var timer2 = "24:00:00";
/*
if you want to get timer from localstorage
var session_timer = localStorage.getItem('timer');
if(session_timer){
console.log('timer',session_timer);
timer2 = session_timer;
}
*/
var interval = setInterval(function() {
var timer = timer2.split(':');
//by parsing integer, I avoid all extra string processing
var hours = parseInt(timer[0], 10);
var minutes = parseInt(timer[1], 10);
var seconds = parseInt(timer[2], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
hours = (minutes < 0) ? --hours : hours;
if (hours < 0) clearInterval(interval);
minutes = (minutes < 0) ? 59 : minutes;
minutes = (minutes < 10) ? '0' + minutes : minutes;
hours = (hours < 10) ? '0' + hours : hours;
if (minutes < 0) clearInterval(interval);
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
minutes = (minutes < 10) ? minutes : minutes;
timer2 = hours+ ':' +minutes + ':' + seconds;
if(hours <= 0 && minutes == 0 && seconds == 0){
// if you want to delete it on local storage
// localStorage.removeItem('timer');
console.log('finish')
// fade out div element
$( "#offer1" ).fadeOut( "slow", function() {
// Animation complete.
});
}
else{
$('#remainingTime').html(timer2);
// if you want to save it on local storage
// localStorage.setItem('timer', timer2);
}
}, 1000);
</script>
createCountdown returns a countdown object with two methods: start and stop.
A countdown has a to date, an onTick callback, and a granularity.
The granularity is the frequency at which the onTick callback is invoked. So if you set a granularity of 1000ms, then the countdown will only tick once a second.
Once the difference between now and to is zero, the onComplete callback is called, and this hides the DOM node.
This solution uses requestAnimationFrame which will have a maximum resolution of about 16 milliseconds. Given that this is the maximum speed that the screen is updated, this is fine for our purposes.
const $ = document.querySelector.bind(document)
const now = Date.now
const raf = requestAnimationFrame
const caf = cancelAnimationFrame
const defaultText = '--:--:--:--'
const createCountdown = ({ to, onTick, onComplete = () => {}, granularityMs = 1, rafId = null }) => {
const start = (value = to - now(), grain = null, latestGrain = null) => {
const tick = () => {
value = to - now()
if(value <= 0) return onTick(0) && onComplete()
latestGrain = Math.trunc(value / granularityMs)
if (grain !== latestGrain) onTick(value)
grain = latestGrain
rafId = raf(tick)
}
rafId = raf(tick)
}
const stop = () => caf(rafId)
return { start, stop }
}
const ho = (ms) => String(Math.trunc((ms/1000/60/60))).padStart(2, '0')
const mi = (ms) => String(Math.trunc((ms%(1000*60*60))/60000)).padStart(2, '0')
const se = (ms) => String(Math.trunc((ms%(1000*60))/1000)).padStart(2, '0')
const ms = (ms) => String(Math.trunc((ms%(1000)))).padStart(3, '0')
const onTick = (value) => $('#output').innerText = `${ho(value)}:${mi(value)}:${se(value)}:${ms(value)}`
const onComplete = () => $('#toFade').classList.add('hidden')
const to = Date.now() + (2 * 60 * 1000)
const { start, stop } = createCountdown({ to, onTick, onComplete })
$('button#start').addEventListener('click', start)
$('button#stop').addEventListener('click', () => (stop(), $('#output').innerText = defaultText))
div#toFade {
opacity: 1;
transition: opacity 5s linear 0s;
}
div#toFade.hidden {
opacity: 0;
}
div {
padding: 20px;
}
<button id="start">Start</button>
<button id="stop">Stop</button>
<div id="output">--:--:--:--</div>
<div id="toFade">This is the element to fade out.</div>
See https://www.w3schools.com/howto/howto_js_countdown.asp for the code used to create a countdown timer
See how to get tomorrow's date: JavaScript, get date of the next day
// Set the date we're counting down to
const today = new Date()
const tomorrow = new Date(today)
tomorrow.setDate(tomorrow.getDate() + 1)
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = tomorrow - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
hours = ("00" + hours).slice(-2);
minutes = ("00" + minutes).slice(-2);
seconds = ("00" + seconds).slice(-2);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = 'Time Remaining: '+hours + ":"
+ minutes + ":" + seconds;
// If the count down is over, hide the countdown
if (distance < 0) {
$("#demo").hide();
}
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
</body>
</html>
Need to create a countdown timer for a online quiz.
Timer should start as soon as user enters web-page.
Tried this piece of code.
<
script >
var fiveMinutes = 3600;
var display = document.getElementById('time');
var myTimer;
function startTime(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
display.textContent = "TIME IS UP!";
clearInterval(myTimer);
}
};
timer();
myTimer = setInterval(timer, 1000);
}
window.onload = function() {
startTime(fiveMinutes, display);
};
Counting is required not from the current moment, but from the date specified in the startTime variable. Let's consider for your convenience that it has exactly the same format as the return value of Date.now ().
i need to get a variable, give it some value (not Date.now ()), and use it as a starting point
thanks beforehand
Not sure if this is what you are looking for, but this is a simple count down timer that displays the time in the window.
const display = document.getElementById('time');
const fiveminutes = 5 * 60 * 1000;
function timer(endTime) {
var myTimer = setInterval(function() {
let now = new Date().getTime();
let diff = endTime - now;
let minutes = Math.floor(diff % (1000 * 60 * 60) / (1000 * 60));
let seconds = Math.floor(diff % (1000 * 60) / 1000);
minutes = minutes < 10 ? `0${minutes}` : minutes;
seconds = seconds < 10 ? `0${seconds}` : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
display.textContent = "TIME IS UP!";
clearInterval(myTimer);
}
}, 100);
}
window.onload = timer(new Date().getTime() + fiveminutes);
span {
font-family: calibri;
font-size: 4em;
}
<body>
<span id="time"></span>
So I'm not sure if this is what you're looking for. This will trigger when the user enters the page. Your comment is confusing though. Do you want this to start when page loads or at a certain time based on a variable?
window.onload(function() {
setTimeout(function() {
// whatever you want to happen after 3600
// i.e. disable input fields for quiz
}, 3600);
}
This is something I'd been working on that I adapted to try to provide a solution for you here. It's still buggy, but maybe it will give you some ideas, and I'll try to edit it when I have some more time. (I expected to have it working by now but need some rest.)
const
timeInput = document.getElementById("timeInput"),
nowBtn = document.getElementById("nowBtn"),
durationInput = document.getElementById("durationInput"),
confirmBtn = document.getElementById("confirmBtn"),
display = document.getElementById("display");
let
startTime,
timeRemaining,
chronos;
document.addEventListener("click", setUpTimer);
timeInput.addEventListener("focus", ()=>{ nowBtn.checked = false; });
function setUpTimer(event){
// Makes sure the button was the target of the click before proceeding
if(event.target == confirmBtn){
if(nowBtn.checked){ // Puts the current time in the time input
const
clickTime = new Date(),
hours = clickTime.getHours();
let minutes = clickTime.getMinutes();
clickTime.setSeconds(clickTime.getSeconds() + 1);
minutes = minutes < 10 ? "0" + minutes : minutes;
timeInput.value = `${hours}:${minutes}`;
}
const
timeInputValue = timeInput.value,
durationInputValue = durationInput.value;
// Validates input (or complains and aborts)
if(!timeInputValue || !durationInputValue){
display.innerHTML = "Please choose a start time and duration"
clearInterval(chronos);
return;
}
const
startArray = timeInputValue.split(":"),
startHours = parseInt(startArray[0]),
startMinutes = parseInt(startArray[1]),
durationInMinutes = parseInt(durationInput.value),
now = new Date();
// Updates global variables that `countdown` function will need
timeRemaining = durationInMinutes * 60;
startTime = new Date();
startTime.setHours(startHours, startMinutes);
// In case startTime is supposed to be tomorrow
const
nowHrs = now.getHours(),
strtHrs = startTime.getHours()
nowMins = now.getMinutes(),
strtMins = startTime.getMinutes();
// If it looks like the hour already passed, it's probably an earlier hour tomorrow
if(strtHrs < nowHrs || (strtHrs == nowHrs && strtMins < nowMins)){
startTime.setDate(startTime.getDate() + 1);
}
// Announces successful timer setup and resets inputs
const
displayedHours = startTime.getHours(),
storedMinutes = startTime.getMinutes(),
displayedMinutes = storedMinutes < 10 ? "0" + storedMinutes : storedMinutes;
display.innerHTML = `A ${durationInMinutes}-minute timer will start ` + `at ${displayedHours}:${displayedMinutes}`;
timeInput.value = "";
nowBtn.checked = false;
durationInput.value = "5";
// `setInterval` calls `countdown` function every second
console.log(startTime.toLocaleString());
clearInterval(chronos);
chronos = setInterval(countdown, 1000);
}
}
function countdown(){
if(timeRemaining <= 0){
display.innerHTML = "TIME IS UP!";
clearInterval(chronos);
}
else{
const now = new Date();
if(now.getTime() >= startTime.getTime()){
updateDisplayedTime(timeRemaining--);
}
}
}
function updateDisplayedTime(totalSeconds){
let
minutes = Math.floor(totalSeconds / 60),
seconds = totalSeconds % 60;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.innerHTML = `${minutes}:${seconds}`;
}
.inputContainer{ margin-bottom: 1em; }
#display{ font-size: 1.7em;}
#nowBtn {margin-left: 1em; }
<div class="inputContainer">
<label>
<div>Start timer at: </div>
<input type="time" id="timeInput" />
</label>
<label>
<input type ="checkbox" id="nowBtn" />
<span>Now</span>
</label>
</div>
<div class="inputContainer">
<label>
<div>Duration (minutes): </div>
<input type="number" value="5" id="durationInput" min="1" max="1440" />
</label>
</div>
<div class="inputContainer">
<button id="confirmBtn">Confirm</button>
</div>
<div id="display"></div>
I found this vanilla JS count down timer that really suits my needs.
http://jsfiddle.net/wr1ua0db/17/
`<body>
<div>Registration closes in <span id="time">05:00</span> minutes!</div>
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
I am looking for a reset function that I could assign to buttons or events. I mean a function that would NOT stop the timer... just reset it back to 5:00 ... so it would automatically go to 4:59... 4:58 ... etc
If you move timer variable to parent scope you'll have access to it from other functions. Then you can reset it in a function called resetTimer. See below:
var timer;
function startTimer(duration, display) {
timer = duration;
var minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
function resetTimer() {
timer = 60 * 5;
}
window.onload = function () {
fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
Here is a fiddle
Try this one. It starts a timer on load and gives you the ability to reset to the initial state.
<style>
#reset:hover {
cursor: pointer;
}
</style>
<div>Time left = <span id="timer">05:00</span><span id="reset" title="Reset Timer"> ↺</span></div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
var upgradeTime = 300; // seconds
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('timer').innerHTML = pad(minutes) + ":" + pad(remainingSeconds);
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('timer').innerHTML = "Completed";
document.getElementById('reset').style.visibility = 'hidden';
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
// function resetTimer() {
// seconds = upgradeTime;
// }
$("#reset").click(function() {
seconds = upgradeTime;
});
</script>
Use something like addEventListener and call the named function.
(function() {
'use strict';
let reset = document.getElementById('reset');
reset.addEventListener('click', function() {
alert('reset');
//add here the function name to call them.
})
})();
<button id="reset">Reset</buton>
I need the javascript countdown timer to work based on the hours. For E.g. If it is 5'o clock then clock should reset from one hour. When it's 6'o clock it should again reset and count down should start.
Like in this website -> https://phorge.com.au/the-dental-edge-webinar
I would like to use following JS. So it would be great if it could be modified.
<script>
var startTime = 59.99; //in Minutes
var doneClass = "done"; //optional styling applied to text when timer is done
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var intervalLoop = setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
document.querySelector("#timer").classList.add(doneClass);
clearInterval(intervalLoop);
}
}, 1000);
}
window.onload = function () {
var setMinutes = 60 * startTime,
display = document.querySelector("#timer");
startTimer(setMinutes, display);
};
/**
* Do not remove this section; it allows our team to troubleshoot and track feature adoption.
* TS:0002-03-069
*/
</script>
Just get the current time and subtract the minutes and seconds from your startTime. As it's a countdown timer per hour you don't care what hour it is, just how many minutes and seconds are left in it.
var startTime = 59.99; //in Minutes
var doneClass = "done"; //optional styling applied to text when timer is done
function startTimer(duration, display) {
var timer = duration,
minutes, seconds;
var intervalLoop = setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
document.querySelector("#timer").classList.add(doneClass);
clearInterval(intervalLoop);
}
}, 1000);
}
window.onload = function() {
var now = new Date();
var hour = now.getHours();
if (hour > 12) {
hour = hour - 11 + " PM"
} else {
hour = hour + 1 + " AM"
}
document.getElementById("hour").textContent = "Until " + hour;
var setMinutes = 60 * (startTime - now.getMinutes() - (now.getSeconds() / 100)),
display = document.querySelector("#timer");
startTimer(setMinutes, display);
};
<span id="timer"></span><br/>
<span id="hour"></span>
I have this Javascript count down timer that works perfectly. Only problem is i can use it for only one time in one page. I want to use it multiple times.
I think script use id ="timer" that is why i am not able to use it multiple times.
Below is the JS code:
<script>
var startTime = 60; //in Minutes
var doneClass = "done"; //optional styling applied to text when timer is done
var space = ' ';
function startTimer(duration, display) {
var timer = duration,
minutes, seconds;
var intervalLoop = setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = "00" + space + minutes + space + seconds;
if (--timer < 0) {
document.querySelector("#timer").classList.add(doneClass);
clearInterval(intervalLoop);
}
}, 1000);
}
window.onload = function() {
var now = new Date();
var hrs = now.getHours();
var setMinutes = 60 * (startTime - now.getMinutes() - (now.getSeconds() / 100)),
display = document.querySelector("#timer");
startTimer(setMinutes, display);
};
</script>
Just declare intervalLoop outside of the startTimer function, it'll be available globally.
var intervalLoop = null
function startTimer(duration, display) {
intervalLoop = setInterval(function() { .... }
})
function stopTimer() {
clearInterval(intervalLoop) // Also available here!
})
window.setInterval(function(){ Your function }, 1000);
Here 1000 means timer 1 sec
I think something like this could be helpful:
Timer object declaration
var timerObject = function(){
this.startTime = 60; //in Minutes
this.doneClass = "done"; //optional styling applied to text when timer is done
this.space = ' ';
return this;
};
timerObject.prototype.startTimer = function(duration, display) {
var me = this,
timer = duration,
minutes, seconds;
var intervalLoop = setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = "00" + me.space + minutes + me.space + seconds;
if (--timer < 0) {
// not sure about this part, because of selectors
document.querySelector("#timer").classList.add(me.doneClass);
clearInterval(intervalLoop);
}
}, 1000);
}
Use it like
var t1 = new timerObject();
var t2 = new timerObject();
t1.startTimer(a,b);
t2.startTimer(a,b);
JS Fiddle example:
UPD1 commented part so the the timer could be stopped
https://jsfiddle.net/9fjwsath/1/