I have this script. I need it to just stop at 0.
function count() {
var startTime = document.getElementById('hms').innerHTML;
var pieces = startTime.split(":");
var time = new Date();
time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timedif = new Date(time.valueOf() - 1000);
var newtime = timedif.toTimeString().split(" ")[0];
document.getElementById('hms').innerHTML = newtime;
setTimeout(count, 1000);
}
count();
<div id='hms'>00:00:05</div>
Stop when string for time is '00:00:00':
function count() {
var startTime = document.getElementById('hms').innerHTML;
// exit function immediately
if(startTime==='00:00:00') return;
var pieces = startTime.split(":");
var time = new Date();
time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timedif = new Date(time.valueOf() - 1000);
var newtime = timedif.toTimeString().split(" ")[0];
document.getElementById('hms').innerHTML = newtime;
setTimeout(count, 1000);
}
count();
<div id="hms">00:00:05</div>
All you need is to add a validity condition.
You can try pieces.some((value) => Number(value) > 0)
Following is a sample code:
Note I took liberty to rename variables to make it more readable.
function countDown() {
const container = document.getElementById('hms');
var startTime = container.innerHTML.trim();
var [hours, minutes, seconds] = startTime.split(":");
if ([hours, minutes, seconds].some((value) => Number(value))) {
var time = new Date();
time.setHours(hours);
time.setMinutes(minutes);
time.setSeconds(seconds);
var timedif = new Date(time.valueOf() - 1000);
var newtime = timedif.toTimeString().split(" ")[0];
container.innerHTML = newtime;
setTimeout(countDown, 1000);
} else {
console.log('Ending countdown...')
}
}
countDown();
<div id='hms'>00:00:05</div>
Related
I tried to show/increment the only time(Hours, Minutes and Seconds) like a timer from getting server side, but it's not working for me.
For this I tried below code.
Can you please help me to run the specified time (Server Time) to run as Timer.
What I have tried:
c#
ScriptManager.RegisterStartupScript(Page, this.GetType(), "close", "OnRunnTimer("+0.21023+");", true);
// JS COde
//Server time I am sending serverTimeP = 0.21023
function OnRunnTimer(timeP) {
setInterval(function () { runJSTimer(timeP); }, 1000);
}
function runJSTimer(serverTimeP) {
var d = new Date();
d.setHours(serverTimeP);
var hours = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
lblJsTimer.SetText(hours + ":" + min + ":" + sec);
}
Can you please help on this.
I'm not sure if I understood, but this is my example of solution to what I think to be your issue.
<body>
<h2 id="timeLabel">Time Label!</h2>
<script type="text/javascript">
var hours = 0;
var min = 0;
var sec = 0;
var serverTime = '2021-02-17T14:34:14.426Z'; // server time example in ISO format
var refreshTimeLabel = function(){
document.getElementById("timeLabel").innerHTML = hours + ":" + min + ":" + sec;
}
var refreshVariables = function () {
var serverTimeDate = new Date(serverTime);
var updatedServerTimeInMilliseconds = serverTimeDate.getTime() + (1000);
var updatedServerTimeDate = new Date(updatedServerTimeInMilliseconds);
serverTime = updatedServerTimeDate.toISOString();
hours = updatedServerTimeDate.getHours();
min = updatedServerTimeDate.getMinutes();
sec = updatedServerTimeDate.getSeconds();
}
var startTimer = function() {
setInterval(function () {
refreshVariables();
refreshTimeLabel();
}, 1000);
}
startTimer();
</script>
</body>
Variant for multiple rows
<body>
<h2 id="timeLabel">Time Label!</h2>
<script type="text/javascript">
var serverTimes = ['2021-02-17T16:34:45.426Z', '2021-02-17T14:54:14.426Z', '2021-02-17T14:00:00.426Z']; // server time array example in ISO format
var refreshServerTimeByIndex = function (index) {
var serverTime = serverTimes[index];
var serverTimeDate = new Date(serverTime);
var updatedServerTimeInMilliseconds = serverTimeDate.getTime() + (1000);
var updatedServerTimeDate = new Date(updatedServerTimeInMilliseconds);
serverTimes[index] = updatedServerTimeDate.toISOString();
}
var refreshServerTimes = function(){
var i;
for(i = 0; i < serverTimes.length; i++){
refreshServerTimeByIndex(i);
}
}
var getTimeTextByDateISO = function(dataISO){
var date = new Date(dataISO);
var hours = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
return hours + ":" + min + ":" + sec;
}
var refreshTimeLabel = function(){
var textLabel = "";
var i;
for(i = 0; i < serverTimes.length; i++){
textLabel += " | " + getTimeTextByDateISO(serverTimes[i]);
}
document.getElementById("timeLabel").innerHTML = textLabel;
}
var startTimer = function() {
setInterval(function () {
refreshServerTimes();
refreshTimeLabel();
}, 1000);
}
startTimer();
</script>
</body>
I need a alert when the countdown hits 00:00:00
<p>
<span id="hms">00:00:05</span>
</body>
<script>
var startTime;
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
} // credits kirlich #http://stackoverflow.com/questions/10730362/get-cookie-by-name
function count() {
if(typeof getCookie('remaining')!= 'undefined')
{
startTime = getCookie('remaining');
}
else if(document.getElementById('hms').innerHTML.trim()!='')
{
startTime = document.getElementById('hms').innerHTML;
}
else
{
var ddddd = new Date();
var hhhhh=ddddd.getHours();
var mmmmm=ddddd.getMinutes();
var sssss=ddddd.getSeconds();
startTime = hhhhh+':'+mmmmm+':'+sssss;
//OR
startTime = ddddd.toTimeString().split(" ")[0]
}
var pieces = startTime.split(":");
var time = new Date();
time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timediff = new Date(time.valueOf()-1000)
var newtime = timediff.toTimeString().split(" ")[0];
document.getElementById('hms').innerHTML=newtime ;
document.cookie = "remaining="+newtime;
setTimeout(count,1000);
}
count();
</script>
</p
<script src="http://code.jquery.com/jquery-latest.js"></script>
<p>
<span id="hms">00:00:05</span>
</body>
<script>
var startTime;
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2)
return parts.pop().split(";").shift();
} // credits kirlich #http://stackoverflow.com/questions/10730362/get-cookie-by-name
function count() {
var check = $("#hms").text();
if (check == "00:00:00") {
myfunction();
}
if (typeof getCookie('remaining') != 'undefined')
{
startTime = getCookie('remaining');
} else if (document.getElementById('hms').innerHTML.trim() != '')
{
startTime = document.getElementById('hms').innerHTML;
} else
{
var ddddd = new Date("00:00:05");
var hhhhh = ddddd.getHours();
var mmmmm = ddddd.getMinutes();
var sssss = ddddd.getSeconds();
startTime = hhhhh + ':' + mmmmm + ':' + sssss;
//OR
startTime = ddddd.toTimeString().split(" ")[0]
}
var pieces = startTime.split(":");
var time = new Date();
time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timediff = new Date(time.valueOf() - 1000)
var newtime = timediff.toTimeString().split(" ")[0];
document.getElementById('hms').innerHTML = newtime;
document.cookie = "remaining=" + newtime;
setTimeout(count, 1000);
}
count();
function myfunction() {
alert("Time Up");
}
</script>
</p
Use this code.
Need to reduce the timing for the set times.
E.g. user logout time is 14:23:30 means need to show the remaining time seconds to the user.
Need to show the counter reducer time in Javascript.
Here is a timer. Like that how to reduce the time from after two minutes.
<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</body>
</html>
I guess this is what you are trying to get:
var initTime = new Date();
var i = 0;
function myTimer(){
i++;
var newTime = new Date(initTime.getTime() - i * 1000);
document.getElementById("demo").innerHTML = newTime.toLocaleTimeString();
}
var myVar = setInterval(myTimer, 1000);
<div id="demo"></div>
If you want to implement timer and want to calculate based on logout time.
var sampleTimer = (function() {
var today = new Date(),
logoutTime = "14:23:30".split(":"),
logoutTimeInsec = new Date(today.getFullYear(), today.getMonth(), today.getDate(), logoutTime[0], logoutTime[1], logoutTime[2]).getTime();
return function() {
var currentTime = new Date().getTime();
console.log('check');
if (logoutTimeInsec - currentTime > 0) {
setTimeout(sampleTimer, 1000);
}
}
}());
I have two count-down timers in my website. One timer would start automatically, but the next one should only start only after the 1st is completed. This should loop on forever, i.e. starting one clock after another.
Here is the code which I tried:
function count() {
var startTime = document.getElementById('hms').innerHTML;
var pieces = startTime.split(":");
var time = new Date();
time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timedif = new Date(time.valueOf() - 1000);
var newtime = timedif.toTimeString().split(" ")[0];
document.getElementById('hms').innerHTML = newtime;
if (newtime !== '00:00:00') {
setTimeout(count, 1000);
} else {
count1();
}
}
count();
function count1() {
var startTime = document.getElementById('hms1').innerHTML;
var pieces = startTime.split(":");
var time = new Date();
time.setHours();
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timedif = new Date(time.valueOf() - 1000);
var newtime = timedif.toTimeString().split(" ")[0];
document.getElementById('hms1').innerHTML = newtime;
if (newtime !== '00:00:00') {
setTimeout(count, 1000);
} else {
count();
}
}
HTML:
<div id="hms">00:00:10</div>
<div id="hms1">00:02:10</div>
I am unable to make this work. Help!!
Your current code is nearly there - with a couple of small issues:
time.setHours is missing a parameter on line 23, should be as follows:
var time = new Date(); time.setHours(pieces[0]);
Line 30 should call the alternate function:
setTimeout(count1, 1000);
Only one counter should be running at a time, so no need to for the last line (count1()).
Here's an updated JSBin.
However, a DRY solution here would be much more appropriate to avoid having to manage two functions:
var currentTimer = 'hms';
var alternateTimer = 'hms1';
function count() {
var timer = document.getElementById(currentTimer);
var startTime = timer.innerHTML;
var pieces = startTime.split(':');
var time = new Date();
time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timedif = new Date(time.valueOf() - 1000);
var newtime = timedif.toTimeString().split(' ')[0];
// Update DOM
timer.innerHTML = newtime;
if(newtime === '00:00:00') {
// Swap the two timers
currentTimer = [alternateTimer, alternateTimer = currentTimer][0];
}
setTimeout(count, 1000);
}
count();
Hope that helps!
count should start a timeout to run count1, and the converse:
initial_count = 5; // say 5 sec. count-down
initial_count1 = 7;
ic = initial_count;
function count() {
ic--
if (ic>=0)
setTimeout(count, 1000); // refresh every 1sec.
else {
ic = initial_count1;
count1();
}
}
function count1() {
ic--
if (ic>=0)
setTimeout(count1, 1000); // refresh every 1sec.
else {
ic = initial_count;
count();
}
}
count(); // start the first alarm.
Add all the remaining of your logic...
function count() {
var startTime = document.getElementById('hms').innerHTML;
var pieces = startTime.split(":");
var time = new Date(); time.setHours(pieces[0]);
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timedif = new Date(time.valueOf() - 1000);
var newtime = timedif.toTimeString().split(" ")[0];
document.getElementById('hms').innerHTML=newtime;
if(newtime!=='00:00:00'){
setTimeout(count, 1000);
}else
{
count1();
}
}
count();
function count1() {
var startTime = document.getElementById('hms1').innerHTML;
var pieces = startTime.split(":");
var time = new Date(); time.setHours();
time.setMinutes(pieces[1]);
time.setSeconds(pieces[2]);
var timedif = new Date(time.valueOf() - 1000);
var newtime = timedif.toTimeString().split(" ")[0];
document.getElementById('hms1').innerHTML=newtime;
if(newtime!=='00:00:00' && newtime!=='00:00:01' ){
setTimeout(count, 1000);
}else
{
count();
}
}
count1();
I'm trying to get server time at start and update it, cause i've to cotnrol some elements with real time. The problem is that if my serverTime doesn't have T the time is NaN on firefox and IE, but if i replace the empty space with T on chrome and IE i've a wrong time.
I now the work-around of replacing white space with T sucks but im outta of time :)
Thanks everybody
At start:
$tmpTime = date("Y-m-d H:i:s");
Head:
<script>
var serverTime = '<?=$tmpTime?>';
serverTime = serverTime.replace(" ", "T");
</script>
Script:
setInterval(function () {
console.log(serverTime);
var tmpTime = new Date(serverTime);
console.log(tmpTime);
var t = tmpTime.getTime();
t = t + 1000;
tmpTime = new Date(t);
serverTime = t;
if (tmpTime.getMinutes() < 10) {
var minutes = "0" + tmpTime.getMinutes();
} else {
var minutes = tmpTime.getMinutes();
};
newTime = tmpTime.getHours() + ":" + minutes;
$('#liveTime').text(newTime);
if ($("#program li[time-id='" + newTime + "'][class='alert']").length !== 0) {
alert("Lo streaming da te programmato sta per iniziare!");
$("#program li[time-id='" + newTime + "'][class='alert']").removeClass("alert");
}
titleToShow();
}, 1000);
function titleToShow() {
$("#program li").each(function () {
var prevTime = $(this).prev("li").attr("time-id");
var thisTime = $(this).attr("time-id");
var nextTime = $(this).next("li").attr("time-id");
currentTime = Date.parse('01/01/2011 ' + newTime);
prevTime = Date.parse('01/01/2011 ' + prevTime);
nextTime = Date.parse('01/01/2011 ' + nextTime);
thisTimeNew = Date.parse('01/01/2011 ' + thisTime);
if (currentTime >= thisTimeNew && currentTime < nextTime && currentTime > prevTime) {
title = $(this).find("p").text();
if (title != $("p#playingTitle").text()) {
$("p#playingTitle").text(title);
}
}
})
}
Don’t use a formated date, just pass the Unix timestamp value to the script (don’t forget to multiply it by 1000, because JS works with milliseconds).
var serverTime = <?php echo time(); ?>;
var tmpTime = new Date(serverTime * 1000);