starting 1 timer clock after another and looping it using javascript - javascript

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();

Related

disable button while retrieving data from local storage and updating the date input

I am trying to implement a function that checks if the date and time I choose have already been chosen before, if so, it gives an error, if not it lets me carry on with adding the ticket. The current function does save options to local storage, however it looks like it doesn't retrieve them for me and allows me to choose the same date twice.
var count = 0;
function store() {
let clickCounter = localStorage.getItem("clickCount");
if (!clickCounter) {
localStorage.setItem("clickCount", 0);
clickCounter = "0";
}
clickCounter = parseInt(clickCounter);
document.getElementById('inc').value = ++count;
if (clickCounter == 100) {
console.log("Limit reached");
return;
} else {
localStorage.setItem("clickCount", clickCounter + 1);
}
console.log("Saving");
var e = document.getElementById("time");
var time = e.options[e.selectedIndex].text;
var date = document.querySelector("input").value;
localStorage.setItem(JSON.stringify(time), date);
console.log(localStorage);
if (!localStorage.getItem("history")) {
localStorage.setItem("history", "[]");
}
const history = JSON.parse(localStorage.getItem("history"));
history.push({ [JSON.stringify(time)]: date });
localStorage.setItem("history", JSON.stringify(history));
console.log(localStorage.getItem("history"));
}
function myDate(date) {
var today = new Date();
var newDate = new Date(date);
var nextWeek = new Date();
var pastWeek = new Date();
nextWeek.setDate(nextWeek.getDate() + 7);
pastWeek.setDate(pastWeek.getDate() - 7);
const dateInput = document.getElementById('date');
if (newDate < pastWeek || newDate > nextWeek) {
document.getElementById("time").disabled = true;
console.log("error")
return;
} else {
document.getElementById("time").disabled = false;
}
}

JS Countdown timer stop at 0

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>

How can I get the "click" function in this code to repeat?

This code executes the "Click" function, but only one time. I would like it to repeated the click function until the timeout occurs.
I wanted to try setInterval instead of setTimeout, but was afraid I would create a race condition.
var M = 12; // january=1
var d = 29; // 1st=1
var h = 11; // 24h time
var m = 12;
var s = 0;
// How long after the target to stop clicking, in milliseconds.
var duration = 100000;
// How long prior to the start time to click, in milliseconds, to
// account for network latency.
var networkLatency = 150;
// HTML ID of the button to click.
var element = "btnbookdates";
// =====================================
// End configuration section
// =====================================
function getMillisecondsLeft() {
var nowDate = new Date();
var targetDate = new Date(y,M-1,d,h,m,s);
return targetDate - nowDate;
}
function click() {
var button = document.getElementById('btnbookdates');
if ( button ) {
window.console.log('clicked at '+getMillisecondsLeft());
button.click();
} else {
window.console.log('nothing to click at '+getMillisecondsLeft());
}
}
if (getMillisecondsLeft() > 0) {
window.console.log('queueing at '+getMillisecondsLeft());
setTimeout(click, getMillisecondsLeft() - networkLatency);
} else if (-getMillisecondsLeft() <= duration) {
click();
} else {
window.console.log('all done at '+getMillisecondsLeft());
}```
If I understood your question correctly, you want the click to stop when everything is done, i.e the else part at the end. You could try something like this:
var M = 12; // january=1
var d = 29; // 1st=1
var h = 11; // 24h time
var m = 12;
var s = 0;
// How long after the target to stop clicking, in milliseconds.
var duration = 100000;
// How long prior to the start time to click, in milliseconds, to
// account for network latency.
var networkLatency = 150;
// HTML ID of the button to click.
var element = "btnbookdates";
// =====================================
// End configuration section
// =====================================
function getMillisecondsLeft() {
var nowDate = new Date();
var targetDate = new Date(y,M-1,d,h,m,s);
return targetDate - nowDate;
}
function click() {
var button = document.getElementById('btnbookdates');
if ( button ) {
window.console.log('clicked at '+getMillisecondsLeft());
button.click();
} else {
window.console.log('nothing to click at '+getMillisecondsLeft());
}
}
var timer ={};
if (getMillisecondsLeft() > 0) {
window.console.log('queueing at '+getMillisecondsLeft());
timer = setInterval(click, getMillisecondsLeft() - networkLatency);
} else if (-getMillisecondsLeft() <= duration) {
click();
} else {
clearInterval(timer);
window.console.log('all done at '+getMillisecondsLeft());
}

perform redirection if event time plus 4 hours is more than current time in js

There is a variable which contains event time. I want to redirect user if event time + 04:38 is more than current time.
Below is the code i have tried:
var deadline = getDayInstance("Monday","08:00:59")
function getDayInstance(day,time) {
const days = {"Sunday":0,"Monday":1,"Tuesday":2,"Wednesday":3,"Thursday":4,"Friday":5,"Saturday":6};
if(days[day]!==undefined)
var dayINeed = days[day];
else
var dayINeed = 2; // for Tuesday
const today = moment().tz("America/Los_Angeles").isoWeekday();
var dt;
// if we haven't yet passed the day of the week that I need:
if (today <= dayINeed) {
dt = moment().tz("America/Los_Angeles").isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
else {
dt = moment().tz("America/Los_Angeles").add(1, 'weeks').isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
console.log("Event Time: "+dt);
var maxLimit = Date.parse(moment(time,'HH:mm:ss').tz("America/Los_Angeles").add({"hours":4,"minutes":43,"seconds":33}).format("YYYY-MM-DDTHH:mm:ss"));
var now = Date.parse(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
if(maxLimit < now)
{
dt = moment().tz("America/Los_Angeles").add(1, 'weeks').isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
window.setVideo = false;
}
console.log(moment(time,'HH:mm:ss').tz("America/Los_Angeles").add({"hours":4,"minutes":43,"seconds":33}).format("YYYY-MM-DDTHH:mm:ss"));
console.log(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
return dt;
}
var maxLimit = Date.parse(moment(deadline,'YYYY-MM-DDTHH:mm:ss').add({"hours":4,"minutes":43,"seconds":33}).format("YYYY-MM-DDTHH:mm:ss"));
var now = Date.parse(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
if(maxLimit>=now){
var redirectTo = $("#lp-pom-button-673").attr('href');
if(redirectTo.length > 3){
window.location.href = redirectTo;
}
else{
window.location.href = "https://******/";
}
}
I need to maintain timezone in calculation.
I got the answer of this after refining the process theoretically and then try to implement it in JS. Below is the new code that can be used for this.
var deadline = getDayInstance("Tuesday", "02:32:00");
var maxLimit,now;
function getDayInstance(day,time) {
const days = {"Sunday":0,"Monday":1,"Tuesday":2,"Wednesday":3,"Thursday":4,
"Friday":5,"Saturday":6};
if(days[day]!==undefined)
var dayINeed = days[day];
else
var dayINeed = 2; // for Tuesday
const today = moment().tz("America/Los_Angeles").isoWeekday();
var dt;
// if we haven't yet passed the day of the week that I need:
if (today <= dayINeed) {
dt = moment().tz("America/Los_Angeles").isoWeekday(dayINeed)
.format('YYYY-MM-DD')+"T"+time;
}
else {
dt = moment().tz("America/Los_Angeles").add(1, 'weeks')
.isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
var d = new Date(dt);
d.setHours(d.getHours() + 4);
d.setMinutes(d.getMinutes() + 43);
d.setSeconds(d.getSeconds() + 32);
max = Date.parse(d);
now = Date.parse(moment().tz("America/Los_Angeles").format('YYYY-MM-DDTHH:mm:ss'));
if(maxLimit < now)
{
dt = moment().tz("America/Los_Angeles").add(1, 'weeks')
.isoWeekday(dayINeed).format('YYYY-MM-DD')+"T"+time;
}
return dt;
}
if(maxLimit>=now){
var redirectTo = $("#lp-pom-button-673").attr('href');
if(redirectTo.length > 3){
window.location.href = redirectTo;
}
else{
window.location.href = "https://******/";
}
}

How to reduce the time counter in Javascript

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);
}
}
}());

Categories