click button need start timer - javascript

hi i want to when i click button, my timer start working. But its just show 1 time.
setInterval(myFunc, 1000);
function myFunc() {
button = document.getElementById("btn");
let date = new Date();
button.addEventListener("click", () => {
document.getElementById("h1text").innerHTML =
date.getHours() + ":" +
date.getMinutes() + ":" +
date.getSeconds();
});
}
i want to work this timer all time, not for one time. like this code but i need to start with button click
setInterval(myFunction, 1000);
function myFunction() {
let d = new Date();
document.getElementById("demo").innerHTML=
d.getHours() + ":" +
d.getMinutes() + ":" +
d.getSeconds();
}

Attach just one click listener, outside the interval. Inside the interval, set the content of the element only if date has been assigned to.
document.getElementById("btn").addEventListener(
'click',
() => {
const fn = () => {
const date = new Date();
document.getElementById("h1text").innerHTML =
date.getHours() + ":" +
date.getMinutes() + ":" +
date.getSeconds();
};
fn();
setInterval(fn, 1000);
},
{ once: true }
);
<h1 id="h1text"></h1>
<button id="btn">click</button>
You might also want to pad the numbers.
document.getElementById("btn").addEventListener(
'click',
() => {
const fn = () => {
const date = new Date();
document.getElementById("h1text").innerHTML =
String(date.getHours()).padStart(2, 0) + ":" +
String(date.getMinutes()).padStart(2, 0) + ":" +
String(date.getSeconds()).padStart(2, 0);
};
fn();
setInterval(fn, 1000);
},
{ once: true }
);
<h1 id="h1text"></h1>
<button id="btn">click</button>

Related

setInterval not updating html element

Basically I'm trying to have my code update the value of an element every second. Problem is my current code only updates it the first time. No errors in console either.
The weird part is that the console.log() keeps running after but the element doesn't update and neither does the time variable
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var date = today.getFullYear() + '/' + String(today.getMonth() + 1).padStart(2, '0') + '/' + String(today.getDate()).padStart(2, '0');
setInterval(function() {
time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var elTime = document.getElementById("time");
elTime.textContent = time;
console.log(time);
}, 1000);
Try this way, the variables also need to be updated each time the setInterval is executed.
(function() {
setInterval(function() {
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var date = today.getFullYear() + '/' + String(today.getMonth() + 1).padStart(2, '0') + '/' + String(today.getDate()).padStart(2, '0');
time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var elTime = document.getElementById("time");
elTime.textContent = time;
console.log(time);
}, 1000);
})()
<div id="time"></div>
You need to re-set "Today" for every tick of the interval. Change to this:
setInterval(function(){
var heute= new Date();
time = heute.getHours() + ":" + heute.getMinutes() + ":" + heute.getSeconds();
var elTime = document.getElementById("time");
elTime.textContent = time;
console.log(time);
}, 1000);
A simple working setInterval program looks like the following.
setInterval(() => {
var elTime = document.getElementById("time");
elTime.textContent = parseInt(elTime.textContent) + 1;
}, 1000);
<div id="time">0</div>
Notice all the code that needs execute is inside the scope of the setInterval function. To fix your problem, add all code inside the scope of the function so it runs every single time like so.
setInterval(function() {
//Variables
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var date = today.getFullYear() + '/' + String(today.getMonth() + 1).padStart(2, '0') + '/' + String(today.getDate()).padStart(2, '0');
time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var elTime = document.getElementById("time");
elTime.textContent = time;
console.log(time);
}, 1000);
<div id="time"></div>
SetInterval is a function call system.
for information: SetInterval can not serve as a precise clock, the durrée between each apple is an indication for the interpreter, and depending on the tasks it must perform elsewhere, it can return beyond the requested period, which is usually the case. For a request of 1000ms, it can realize the call after 1004ms, 1020ms, or even more.
and more easy to use native JS time formating => https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString
const elTime = document.getElementById("time")
ShowTime() // first attempt
setInterval(ShowTime, 1000) // next ones
function ShowTime()
{
let t_Now = new Date()
elTime.textContent = t_Now.toLocaleTimeString('default', { hour12:false } )
}
<p id="time"></p>

document.lastModified only displays current date?

I've been looking for a way to display the date the page last was updated.
Now I've been searching around, and everything points to the document.lastModified function, but however I've tried to fix it, it always shows the current date.
I've tried this example:
function lastModified() {
var modiDate = new Date(document.lastModified);
var showAs = modiDate.getDate() + "-" + (modiDate.getMonth() + 1) + "-" + modiDate.getFullYear();
return showAs
}
function GetTime() {
var modiDate = new Date();
var Seconds
if (modiDate.getSeconds() < 10) {
Seconds = "0" + modiDate.getSeconds(); }
else {
Seconds = modiDate.getSeconds(); }
var modiDate = new Date();
var CurTime = modiDate.getHours() + ":" + modiDate.getMinutes() + ":" + Seconds
return CurTime }
document.write("Last updated on ");
document.write(lastModified() + " # " + GetTime());
document.write(" [D M Y 24 Hour Clock]"); document.write("");
Or a simple one like this:
<SCRIPT LANGUAGE="JavaScript">
var t = new Date(document.lastModified);
document.write("<I>Last Updated: "+document.lastModified+"</I><BR>");
document.write("<I>Last Updated: "+t+"</I><BR>");
</SCRIPT>
Is there any other way to do this?
.. Without taking a 3 years tech-class?
Press here to see the scripts live
Because you are modifying it currently. Check this out for example.
To make this work based on your requirement, checkout this link and this link
check this it will help u
Put this on the page at the bottom:
<script type="text/javascript" src="js_lus.js"></script>
Name the file whatever you want. Example: js_lus.js Make sure src=""
path is correct for all your pages.
function lastModified() {
var modiDate = new Date(document.lastModified);
var showAs = modiDate.getDate() + "-" + (modiDate.getMonth() + 1) + "-" +
modiDate.getFullYear();
return showAs
}
function GetTime() {
var modiDate = new Date();
var Seconds
if (modiDate.getSeconds() < 10) {
Seconds = "0" + modiDate.getSeconds();
} else {
Seconds = modiDate.getSeconds();
}
var modiDate = new Date();
var CurTime = modiDate.getHours() + ":" + modiDate.getMinutes() + ":" + Seconds
return CurTime
}
document.write("Last updated on ")
document.write(lastModified() + " # " + GetTime());
document.write(" [D M Y 24 Hour Clock]")
document.write("");

Dynamically update time without refreshing the page

<html>
<head>
<script>
function updateClock() {
var time = now.getHours() + ':' + now.getMinutes(),
document.getElementById('current').innerHTML = time;
setTimeout(updateClock, 1000);
}
</script>
</head>
<body onload="updateClock()">
<p id="current"> </p>
</body>
</html>
Above is the code for dynamically update real time, it is not showing any thing on the browser. Would really appreciate help
Thank you.
Show time using Js :
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('current').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
<body onload="startTime()">
<p id="current">Time loading..</p>
</body>
OR
Your code edited:
function updateClock() {
var now = new Date();
var time = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
document.getElementById('current').innerHTML = time;
setTimeout(updateClock, 1000);
}
<body onload="updateClock()">
<p id="current"></p>
</body>
You were missing var now = new Date(); and also now.getSeconds();.
There are some errors in updateClock:
function updateClock() {
var now = new Date()
var time = now.getHours() + ':' + now.getMinutes();
document.getElementById('current').innerHTML = time;
setTimeout(updateClock, 1000);
}
now must be a Date object.
now needed to be a date object
You had a comma instead of a semicolon after now.getMinutes(),
I recommend using
* padding
* setInterval
* window.onload instead of body onload
I added seconds to show it updates. If you only need hours and minutes, change the interval time to 10000 or so.
function pad(num) {
return String("0"+num).slice(-2);
}
function updateClock() {
var now = new Date();
var time = pad(now.getHours()) + ':' + pad(now.getMinutes()) + ":" + pad(now.getSeconds());
document.getElementById('current').innerHTML = time;
}
window.onload = function() {
setInterval(updateClock, 500); // use a shorter interval for better update
}
<p id="current"></p>

Adapting a stopwatch script to return minutes and seconds elapsed

I have found a script that counts seconds and minutes. I would like get the minutes and seconds value and store it in a variable when I clicked a stop button, how should I do it?
var initialTime = Date.now();
window.setInterval(checkTime, 100);
function checkTime( miliseconds) {
var timeDifference = Date.now() - initialTime;
var formatted = convertTime(timeDifference);
if(seconds > 30 || minutes > 0) {
$('#timer').html('<span style="color: red">' + minutes + ': ' + seconds + '</span>');
} else {
$('#timer').html('<span style="color: black">' + minutes + ': ' + seconds + '</span>');
}
}
function convertTime(miliseconds) {
totalSeconds = Math.floor(miliseconds/1000);
minutes = Math.floor(totalSeconds/60);
seconds = totalSeconds - minutes * 60;
return minutes,seconds;
}
Make a button and attach an event on it. Then clear the interval when the button is clicked:
$("button").on('click', function() {
window.clearInterval(interval);
});
Demo: https://jsfiddle.net/76t086c2/
You can either get the value from the div#timer or set the minutes/seconds in an input and when the button is clicked, get the value.
You can return valued from your function like this:
HTML
<button id="stop">Stop</button>
<button id="start" disabled>Start</button>
<div id="timer"></div>
<div id="output"></div>
JavaScript
var initialTime = Date.now();
var timer = window.setInterval(checkTime, 100);
function checkTime() {
var timeDifference = Date.now() - initialTime;
var formatted = convertTime(timeDifference);
if(formatted.seconds > 30 || formatted.minutes > 0) {
$('#timer').html('<span style="color: red">' + formatted.minutes + ': ' + formatted.seconds + '</span>');
} else {
$('#timer').html('<span style="color: black">' + formatted.minutes + ': ' + formatted.seconds + '</span>');
}
return formatted;
}
function convertTime(miliseconds) {
var totalSeconds = Math.floor(miliseconds/1000);
var minutes = Math.floor(totalSeconds/60);
var seconds = totalSeconds - minutes * 60;
return {'seconds': seconds,'minutes':minutes};
}
function toggle() {
$('#start, #stop').prop('disabled', function(i, v) { return !v; });
}
$('#stop').on('click',function() {
clearInterval(timer);
toggle();
var t = checkTime();
$('#output').html('Time was stopped at: '+t.minutes + ':' + t.seconds)
})
$('#start').on('click',function() {
initialTime = Date.now();
timer = window.setInterval(checkTime, 100);
toggle();
})
You can see it working here: https://jsfiddle.net/jqy0ehbp/3/
Ok, you have 2 dates.
get the difference in miliseconds and format the result.
var initialTime = new Date(2016, 2, 09, 10, 00, 0);
var now = new Date(Date.now());
var dateDifference = (now - initialTime);
console.log('Diff miliseconds = ', dateDifference);
console.log('Result: ', FormatMiliseconds(dateDifference));
You can view an example in this fiddle:
jsfiddle

Having issue with setInterval

I am having an issue with the setInterval() function in javascript where it will print to my page once and it will not continue to do so. I was wondering if maybe this is a browser issue or something i did wrong.
function printTime() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
document.write(hours + ":" + minutes + ":" + seconds + "<br/>");
}
setInterval("printTime()", 1000);
Apart from the poor practice of using "functionName()" instead of just functionName, the code will never work if the interval is beyond the page loading.
document.write will wipe the page after load
Here is a better solution:
<div id="time"></div>
<script>
function pad(str) { return ("0"+str).slice(-2)}
function printTime() {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
document.getElementById("time").innerHTML+=pad(hours) + ":" + pad(minutes) + ":" + pad(seconds) + "<br/>";
}
setInterval(printTime, 1000);
</script>

Categories