Show Date.getTime() javascript into html - javascript

I am trying to make a stopwatch using html and javascript on my website.
Here is what I tried:
<!DOCTYPE HTML>
<html>
<script>
Date.setTime(0);
</script>
<body>
<p>Time: <script>document.write(Date.getTime());</script></p>
</body>
</html>
I want it to show milliseconds since load. I'm doing it on KhanAcademy. Does anybody know how to do this?
Also, somewhat, weirdly, there are no errors

If you want to show the milliseconds since the page load you need to update it using setInterval()
<!DOCTYPE HTML>
<html>
<body>
<p>Time: <span id="msec"></span> </p>
</body>
<script>
var msec = 0;
msec = setInterval(function(){
msec = msec + 1;
document.getElementById("msec").innerText = msec;
},1)
</script>
</html>

You likely meant to do this
NOTE the script tags have to be AFTER the span - it needs to exist.
let d = new Date();
d.setTime(1000)
const span = document.getElementById("time");
const tId = setInterval(function() {
if (d.getTime() <= 0) clearInterval(tId);
span.textContent = d.getTime();
d.setTime(d.getTime() - 10)
}, 10);
<span id="time"></span>
but that is the same as doing this
let d = 1000;
const span = document.getElementById("time");
const tId = setInterval(function() {
span.textContent = d-=10
if (d <= 0) clearInterval(tId);
}, 10)
<span id="time"></span>
Using the window load event so the script can stay in the head
Herre I am counting up
window.addEventListener("load", function() { // on page load
let d = 0;
const span = document.getElementById("time");
const tId = setInterval(function() {
span.textContent = d += 10
if (d >= 1000) clearInterval(tId);
}, 10);
});
<span id="time"></span>

You have to set an interval to update calculate the duration since starting the website (I choose 1 ms). The script has to be written in the code after the HTML-element is declared.
var start = performance.now();
setInterval(function() {
let time = performance.now();
document.getElementById('duration').innerHTML = 'Dauer: ' + (time - start) + ' ms.';
}, 1);
<div id='duration'></div>

Related

How to make my countdown timer don't start from the beginning when refreshing the page

I got a countdown code from this repository and i made some changes, and i want to make the countdown don't start from the beginning when i refresh the page, my Js code is :
var timeleft =5400;
var startTime = 0;
var currentTime = 0;
function convertSeconds(s) {
var decimal = (s/3600) - Math.floor((s/3600))
var h = floor(s/3600);
var min = floor(decimal * 60) ;
var sec = s % 60;
return nf(h, 2) + ':' + nf(min, 2) + ':' + nf(sec, 2);
}
function setup() {
noCanvas();
startTime = millis();
var timer = select('#timer');
timer.html(convertSeconds(timeleft - currentTime));
var interval = setInterval(timeIt, 1000);
function timeIt() {
currentTime = floor((millis() - startTime) / 1000);
timer.html(convertSeconds(timeleft - currentTime));
if (currentTime == timeleft) {
clearInterval(interval);
}
}
}
My HTML code :
<html>
<head>
<meta charset="UTF-8">
<script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
<script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/addons/p5.dom.js"></script>
<script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/addons/p5.sound.js"></script>
<script language="javascript" type="text/javascript" src="chrono.js"></script>
</head>
<body>
<p id="timer"></p>
</body>
</html>
You could store the current counter value to local storage (cookie or other options if using html 5) and upon load of the page read it's value and start your timer based on that.
Andrew suggested storing a timestamp every time the interval begins to storage. Then upon load you get the delta by subtracting the current timestamp by the stored timestamp

how to add to an HTML time element

How can I use javascript to add to an existing HTML Time element. I have an html time element and want to be able to press a button that adds one minute to the current time. I don't want to use input type time. This is my existing code:
<body>
<time id = 'time'> 10:00 </time>
<button onclick = "addTime();">addTime</button>
<script>
function addTime(){
document.getElementById('time').innerHTML += '01:00'
}
</script>
</body>
but this just appends the time as a string. Is there an easy way to fix this?
You can use Date.prototype.setMinutes() with first two numbers of .innerHTML of element, Date.prototype.setSeconds() with parameter 0
<body>
<time id='time'> 10:00 </time>
<button onclick="addTime();">addTime</button>
<script>
const time = document.getElementById('time')
let date = new Date();
function addTime() {
date.setMinutes(1 + +time.innerHTML.match(/\d{2}/)[0]);
date.setSeconds(0);
time.innerHTML = String(date).slice(19, 24);
}
</script>
</body>
In html you can put this code:
<time id='time'> <label id="hour">10</label>:<label id="second">00</label> </time>
<button onclick="addTime();">addTime</button>
You can run this function:
function addTime() {
var h = parseInt(document.getElementById('hour').innerHTML);
var s = parseInt(document.getElementById('second').innerHTML);
s++;
var add = "0";
if (s < 10) {
add = "0" + s;
}
else {
add = s;
}
if (s == 60) {
add = "00";
h = h + 1;
}
if (h == 25) {
h = 1;
}
document.getElementById('hour').innerHTML = h;
document.getElementById('second').innerHTML = add;
}

Format time to minutes and seconds in countdown/timer

I am building a pomodoro clock/countdown, but have an issue with formatting selected time to minutes/hours/seconds. I have tried to multiply the secs variable with 60 (secs*=60), but it makes a mess and I can't figure out how to fix it. So, I would like it to "know" that it needs to count down from 25 minutes - in 25:00 format, or more/less(hh:mm:ss) if the user chooses so with + and - buttons. All help very appreciated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1 id="num">25 min</h1>
<div id="status"></div>
<button onclick='countDown(secs, "status")'>Start countdown</button>
<button onclick='increaseNumber()'>+</button>
<button onclick='decreaseNumber()'>-</button>
<script src="script.js"></script>
</body>
</html>
and here is javascript:
var num = document.getElementById('num').innerHTML;
var secs = parseInt(num);
function countDown(secs, elem) {
var element = document.getElementById(elem);
secs--;
var timer = setTimeout(function() {
countDown(secs, elem);
}, 1000);
//secs *= 60;
if(secs%60 >= 10){ //10 - if it's not a single digit number
document.getElementById('num').innerHTML = (Math.floor(secs/60) + ":" + secs%60);
}
else{
document.getElementById('num').innerHTML = (Math.floor(secs/60) + ":" + "0" + secs%60);
}
element.innerHTML = "Please wait for "+secs+" minutes";
//if timer goes into negative numbers
if(secs < 1){
clearTimeout(timer);
element.innerHTML = '<h2>Countdown complete!</h2>';
element.innerHTML += 'Click here now';
}
}
function increaseNumber() {
secs += 5;
document.getElementById('num').innerHTML = secs + ' min';
}
function decreaseNumber() {
if(secs >= 10) {
secs -= 5;
document.getElementById('num').innerHTML = secs + ' min';
}
}
Is there a reason you're doing it by hand ?
If you don't mind using a library, moment.js does a very good job at time manipulations. It's lightweight and very easy to use.
If you have to do it by hand because of some limitations, what are they ?
For reference:
//Creates a moment. Its value is the time of creation
var timer = moment();
//add 60 seconds to the timer
timer.add(60, 's');
//Removes 1 minutes from the timer
timer.subtract(1, 'm');
Sources :
Add
Substract
Try this countDown function:
function countDown(secs, elem) {
var element = document.getElementById(elem);
element.innerHTML = "Please wait for "+secs+" minutes";
var second = 0;
var timer = setInterval(function(){
var extraZero = second < 10 ? '0' : '';
document.getElementById('num').innerHTML = secs + ":" + extraZero + second;
if (second-- === 0) {
second = 59;
if (secs-- === 0){
clearInterval(timer);
element.innerHTML = '<h2>Countdown complete!</h2>';
element.innerHTML += 'Click here now';
}
}
}, 1000);
}
Since you are counting down the seconds, it is making more sense to use setInterval instead of setTimeout.

Forcing page refresh at a specific time with timezone

I'm trying to force a page to refresh with js at a specific time, after digging around I found the script below. However, it doesn't appear to take into consideration timezones. How would I implement that?
<html>
<head>
<title></title>
<script type="text/javascript">
function refreshAt(hours, minutes, seconds) {
var now = new Date();
var then = new Date();
if(now.getHours() > hours ||
(now.getHours() == hours && now.getMinutes() > minutes) ||
now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
then.setDate(now.getDate() + 1);
}
then.setHours(hours);
then.setMinutes(minutes);
then.setSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
refreshAt(15,06,0); //Will refresh the page at 3:06pm
</script>
</head>
<body onLoad="setInterval('getCurrentTime()', 1000);">
<div id="time"></div>
content
</body>
</html>
Here you go, reload will occur for every user exactly as you define in global vars in script:
EDIT!!! I had bug in code so I have updated the script...
EDIT working example:
http://simplestudio.rs/yard/tinediffredir/content.html
<html>
<head>
<title>Chk diff and reload if match</title>
<script>
var reload_time = "15060"; // this is 15:06:00 - change to desired reload time
var reload_hour_diff = 15; // for cheking diff - change to desired hours
var reload_minute_diff = 6; // for cheking diff - change to desired minutes
var time_zone_offset = "-5"; // globally looking from GMT time, change this according to DST
var reload_time_checker = setInterval(function(){reload_page()},300);
var diff = null;
function chk_reload_moment(offset) {
dat = new Date();
utc = dat.getTime() + (dat.getTimezoneOffset() * 60000);
default_date = new Date(utc + (3600000*offset));
var default_year = default_date.getFullYear();
var default_month = default_date.getMonth();
var default_day = default_date.getDate();
var default_hour = default_date.getHours();
var default_minutes = default_date.getMinutes();
var default_seconds = default_date.getSeconds();
user_date = new Date();
var user_year = user_date.getFullYear();
var user_month = user_date.getMonth();
var user_day = user_date.getDate();
var user_hour = user_date.getHours();
var user_minutes = user_date.getMinutes();
var user_seconds = user_date.getSeconds();
user_current = user_hour+""+user_minutes+""+user_seconds;
default_current_f = default_day+"/"+default_month+"/"+default_year+" "+default_hour+":"+default_minutes+":"+default_seconds;
user_current_f = user_day+"/"+user_month+"/"+user_year+" "+user_hour+":"+user_minutes+":"+user_seconds;
var timeEnd = new Date(user_current_f);
var timeEndH = timeEnd.getHours();
var timeEndM = timeEnd.getMinutes();
var new_reload_minute_diff = 60+reload_minute_diff;
diff = (timeEndH - reload_hour_diff + 12) + " hours " + (new_reload_minute_diff - timeEndM) + " minutes";
if (user_current == reload_time) {
return true;
}
else {
return false;
}
}
function reload_page() {
var chktime = chk_reload_moment(time_zone_offset);
if (chktime) {
window.location.reload();
}
else {
var timer_div = document.getElementById('timer');
timer_div.innerHTML = "remaining: " + diff + " until new content";
}
}
</script>
</head>
<body>
<div id="timer">
</div>
</body>
</html>
I think it is clear how to configure it but if you have some problems feel free to ask...

Clock in Javascript

I have made a clock in javascript but its a static clock. What changes I need to do in the following code so that it updates with every second.
<html>
<head>
<title>Javascript Clock</title>
<script type="text/javascript">
function clk() {
var a=new Date();
document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
}
</script>
</head>
<body>
<input type="button" onclick="clk()" value="Display Clock" />
<p id="disp">Clock Space</p>
</body>
</html>
You can use setInterval to run your clk() function every second:
setInterval(clk, 1000); // run clk every 1000ms
MDN on setInterval
As nnnnnn points out, the timer interval probably won't be synchronized with the passage of an actual, real-time second, so using an interval like 100ms might not be a bad idea.
You can add setTimeout(clk,1000); to your function,as bellow:
function clk() {
var a=new Date();
document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
setTimeout(clk,1000);
}
A JavaScript digital clock from system time, can also manually set. :-)
function timer(h,m,s){
var sec;
var min;
var hrs;
var day;
if(((s<=59) && (s>=0)) && ((m<=59) && (m>=0)) && ((h<=23) && (h>=0))){
sec=s;
min=m;
hrs=h;
//set parent element id 'lga' to your id
var parent = document.getElementById('lga');
parent.innerHTML = '';
var child = document.createElement('div');
child.id = "thanesh";
child.style = 'font-size:20px';
parent.appendChild(child);
setInterval(function(){
sec++;
if(sec==60){sec=0;min++;}
if(min==60){min=0;hrs++;}
if(hrs==24){hrs = 0; min = 0; sec = 0;}
if(hrs<=12){
day = 'AM';
}else{
day = 'PM';
}
document.getElementById('thanesh').innerHTML = '<table style="background-color:#f5f5f5;"><tr><td><div id="hh">0</div><td>'
+hrs+' : <td><div id="mm">0</div><td>'
+min+' : <td><div id="ss">0</div><td>'
+sec+' <td>'
+day+'</td></td></td></td></td></td></td></tr></table>';
if(sec>9){
document.getElementById('ss').style.display = "none";
}else if(sec==0){
document.getElementById('ss').style.display = "block";
}
if(min>9){
document.getElementById('mm').style.display = "none";
}else if(min==0){
document.getElementById('mm').style.display = "block";
}
if(hrs>9){
document.getElementById('hh').style.display = "none";
}else if(hrs==0){
document.getElementById('hh').style.display = "block";
}
},
1000);
}else{
alert("Check time inputs...!");
}
}
//Set Hour, Minutes, Seconds by JS / manually
var date = new Date();
var hst = date.getHours();
var mst = date.getMinutes();
var sst = date.getSeconds();
timer(hst,mst,sst);
Since your "update every second" of the real clock competes with other computer tasks, the delay before the next real clock tic will be less than 1000 ms very often. So, better use setTimeout instead of setInterval. In fact, we just need to twist a little bit the end of the denied 姚先进's solution here arround, resulting in:
function clk() {
var a=new Date();
document.getElementById("disp").innerHTML=a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds() ;
setTimeout(clk, 1000 - a % 1000);
}
This is my clock solution since 2007.
here we go
<html>
<head>
<title>Javascript Clock</title>
<script type="text/javascript">
function clk() {
setInterval(() => {
var a = new Date();
document.getElementById("disp").innerHTML = a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds();
},1000);
}
</script>
</head>
<body>
<input type="button" onclick="clk()" value="Display Clock" />
<p id="disp">Clock Space</p>
</body>
</html>

Categories