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>
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>
I have some code below which is a forward timer, when I press start it starts counting in hh/mm/ss, and when I press Display time taken it shows time taken in hh/mm/ss inside the tag, and resets the counter to zero on button click and starts counting from zero.
My problem is that the timer initially only starts when I press the start button.
I want to make the timer start automatically when the window loads and remove the start button.
How can be this be achieved?
window.onload = () => {
let hour = 0;
let minute = 0;
let seconds = 0;
let totalSeconds = 0;
let intervalId = null;
function startTimer() {
++totalSeconds;
hour = Math.floor(totalSeconds / 3600);
minute = Math.floor((totalSeconds - hour * 3600) / 60);
seconds = totalSeconds - (hour * 3600 + minute * 60);
document.getElementById("hour").innerHTML = hour;
document.getElementById("minute").innerHTML = minute;
document.getElementById("seconds").innerHTML = seconds;
}
document.getElementById('start-btn').addEventListener('click', () => {
intervalId = setInterval(startTimer, 1000);
})
document.getElementById('Displplaytimetaken').addEventListener('click', () => {
document.getElementById("timetaken").innerHTML = minute + "minutes" + seconds + "seconds";
reset();
});
function reset() {
totalSeconds = 0;
document.getElementById("hour").innerHTML = '0';
document.getElementById("minute").innerHTML = '0';
document.getElementById("seconds").innerHTML = '0';
}
}
<h1 style="font-size:24px;">Time Taken:
<h1 id="timetaken"></h1>
<button id="start-btn">Start</button>
<button id="Displplaytimetaken">Display time taken</button>
window.onload = () => {
let hour = 0;
let minute = 0;
let seconds = 0;
let totalSeconds = 0;
let intervalId = null;
intervalId = setInterval(startTimer, 1000);
function startTimer() {
++totalSeconds;
hour = Math.floor(totalSeconds / 3600);
minute = Math.floor((totalSeconds - hour * 3600) / 60);
seconds = totalSeconds - (hour * 3600 + minute * 60);
document.getElementById("hour").innerHTML = hour;
document.getElementById("minute").innerHTML = minute;
document.getElementById("seconds").innerHTML = seconds;
}
document.getElementById('Displplaytimetaken').addEventListener('click', () => {
document.getElementById("timetaken").innerHTML = minute + "minutes" + seconds + "seconds";
reset();
});
function reset() {
totalSeconds = 0;
document.getElementById("hour").innerHTML = '0';
document.getElementById("minute").innerHTML = '0';
document.getElementById("seconds").innerHTML = '0';
}
}
<h1 style="font-size:24px;">Time Taken:
<h1 id="timetaken">
</h1>
<h2> <span id="hour"></span>
<span id="minute"></span>
<span id="seconds"></span>
</h2>
<button id="Displplaytimetaken">Display time taken</button>
Run it and hope your problem get solved.
Try
<body onload="startTimer()">
In your HTML.
Does that help?
I am making a riddle, where the people who try to solve it have 45 minutes to solve the riddle, and when they don't answer correctly, I want the timer to go down five minutes, to prevent them from just guessing the answers. How could I do it, I am very new to using javascript, this is the first time I'm working with it.
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
var cat1 = ($("input[#name=Verdachte]:checked").val() != "2");
var cat2 = ($("input[#name=Moordwapen]:checked").val() != "4");
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) {
start = Date.now() + 1000;
}
};
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fortyfiveMinutes = 60 * 45,
display = document.querySelector('#time');
startTimer(fortyfiveMinutes,display);}
I want the timer to go down five minutes when cat1 is true, and/or when cat2 is true.
Inside of timer, just check the input, and if it is true, disable the input and increase the time:
var cat1 = $("input[#name=Verdachte]:checked");
if(cat1.val() === "2") {
cat1.val("you are right :)");
cat1.attr("disabled", true);
start -= 1000 * 60 * 5;
}
//...
... that would be even more elegant with event handlers ...
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
I'm new to JavaScript and I'm trying to write a code which calculates the time elapsed from the time a user logged in to the current time.
Here is my code:-
function markPresent() {
window.markDate = new Date();
$(document).ready(function() {
$("div.absent").toggleClass("present");
});
updateClock();
}
function updateClock() {
var markMinutes = markDate.getMinutes();
var markSeconds = markDate.getSeconds();
var currDate = new Date();
var currMinutes = currDate.getMinutes();
var currSeconds = currDate.getSeconds();
var minutes = currMinutes - markMinutes;
if(minutes < 0) { minutes += 60; }
var seconds = currSeconds - markSeconds;
if(seconds < 0) { seconds += 60; }
if(minutes < 10) { minutes = "0" + minutes; }
if(seconds < 10) { seconds = "0" + seconds; }
var hours = 0;
if(minutes == 59 && seconds == 59) { hours++; }
if(hours < 10) { hours = "0" + hours; }
var timeElapsed = hours+':'+minutes+':'+seconds;
document.getElementById("timer").innerHTML = timeElapsed;
setTimeout(function() {updateClock()}, 1000);
}
The output is correct upto 00:59:59 but after that that O/P is:
00:59:59
01:59:59
01:59:00
01:59:01
.
.
.
.
01:59:59
01:00:00
How can I solve this and is there a more efficient way I can do this?
Thank you.
No offence, but this is massively over-enginered. Simply store the start time when the script first runs, then subtract that from the current time every time your timer fires.
There are plenty of tutorials on converting ms into a readable timestamp, so that doesn't need to be covered here.
var start = Date.now();
setInterval(function() {
document.getElementById('difference').innerHTML = Date.now() - start;
// the difference will be in ms
}, 1000);
<div id="difference"></div>
There's too much going on here.
An easier way would just be to compare markDate to the current date each time and reformat.
See Demo: http://jsfiddle.net/7e4psrzu/
function markPresent() {
window.markDate = new Date();
$(document).ready(function() {
$("div.absent").toggleClass("present");
});
updateClock();
}
function updateClock() {
var currDate = new Date();
var diff = currDate - markDate;
document.getElementById("timer").innerHTML = format(diff/1000);
setTimeout(function() {updateClock()}, 1000);
}
function format(seconds)
{
var numhours = parseInt(Math.floor(((seconds % 31536000) % 86400) / 3600),10);
var numminutes = parseInt(Math.floor((((seconds % 31536000) % 86400) % 3600) / 60),10);
var numseconds = parseInt((((seconds % 31536000) % 86400) % 3600) % 60,10);
return ((numhours<10) ? "0" + numhours : numhours)
+ ":" + ((numminutes<10) ? "0" + numminutes : numminutes)
+ ":" + ((numseconds<10) ? "0" + numseconds : numseconds);
}
markPresent();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="timer"></div>
Here is a solution I just made for my use case. I find it is quite readable. The basic premise is to simply subtract the timestamp from the current timestamp, and then divide it by the correct units:
const showElapsedTime = (timestamp) => {
if (typeof timestamp !== 'number') return 'NaN'
const SECOND = 1000
const MINUTE = 1000 * 60
const HOUR = 1000 * 60 * 60
const DAY = 1000 * 60 * 60 * 24
const MONTH = 1000 * 60 * 60 * 24 * 30
const YEAR = 1000 * 60 * 60 * 24 * 30 * 12
// const elapsed = ((new Date()).valueOf() - timestamp)
const elapsed = 1541309742360 - timestamp
if (elapsed <= MINUTE) return `${Math.round(elapsed / SECOND)}s`
if (elapsed <= HOUR) return `${Math.round(elapsed / MINUTE)}m`
if (elapsed <= DAY) return `${Math.round(elapsed / HOUR)}h`
if (elapsed <= MONTH) return `${Math.round(elapsed / DAY)}d`
if (elapsed <= YEAR) return `${Math.round(elapsed / MONTH)}mo`
return `${Math.round(elapsed / YEAR)}y`
}
const createdAt = 1541301301000
console.log(showElapsedTime(createdAt + 5000000))
console.log(showElapsedTime(createdAt))
console.log(showElapsedTime(createdAt - 500000000))
For example, if 3000 milliseconds elapsed, then 3000 is greater than SECONDS (1000) but less than MINUTES (60,000), so this function will divide 3000 by 1000 and return 3s for 3 seconds elapsed.
If you need timestamps in seconds instead of milliseconds, change all instances of 1000 to 1 (which effectively multiplies everything by 1000 to go from milliseconds to seconds (ie: because 1000ms per 1s).
Here are the scaling units in more DRY form:
const SECOND = 1000
const MINUTE = SECOND * 60
const HOUR = MINUTE * 60
const DAY = HOUR * 24
const MONTH = DAY * 30
const YEAR = MONTH * 12
We can also use console.time() and console.timeEnd() method for the same thing.
Syntax:
console.time(label);
console.timeEnd(label);
Label:
The name to give the new timer. This will identify the timer; use the same name when calling console.timeEnd() to stop the timer and get the time output to the console.
let promise = new Promise((resolve, reject) => setTimeout(resolve, 400, 'resolved'));
// Start Timer
console.time('x');
promise.then((result) => {
console.log(result);
// End Timer
console.timeEnd('x');
});
You can simply use performance.now()
Example:
start = performance.now();
elapsedTime = performance.now() - start;
var hours = 0;
if(minutes == 59 && seconds == 59)
{
hours = hours + 1;
minutes = '00';
seconds == '00';
}
I would use the getTime() method, subtract the time and then convert the result into hh:mm:ss.mmm format.
I know this is kindda old question but I'd like to apport my own solution in case anyone would like to have a JS encapsulated plugin for this. Ideally I would have: start, pause, resume, stop, reset methods. Giving the following code all of the mentioned can easily be added.
(function(w){
var timeStart,
timeEnd,
started = false,
startTimer = function (){
this.timeStart = new Date();
this.started = true;
},
getPartial = function (end) {
if (!this.started)
return 0;
else {
if (end) this.started = false;
this.timeEnd = new Date();
return (this.timeEnd - this.timeStart) / 1000;
}
},
stopTime = function () {
if (!this.started)
return 0;
else {
return this.getPartial(true);
}
},
restartTimer = function(){
this.timeStart = new Date();
};
w.Timer = {
start : startTimer,
getPartial : getPartial,
stopTime : stopTime,
restart : restartTimer
};
})(this);
Start
Partial
Stop
Restart
What I found useful is a 'port' of a C++ construct (albeit often in C++ I left show implicitly called by destructor):
var trace = console.log
function elapsed(op) {
this.op = op
this.t0 = Date.now()
}
elapsed.prototype.show = function() {
trace.apply(null, [this.op, 'msec', Date.now() - this.t0, ':'].concat(Array.from(arguments)))
}
to be used - for instance:
function debug_counters() {
const e = new elapsed('debug_counters')
const to_show = visibleProducts().length
e.show('to_show', to_show)
}