javascript compare current time to variable every minute - javascript

I have a start date defined in a database and I need to know when the start date is greater then the current time. I've tried using setInterval, but I can't access the updated time outside the setInterval function.
This is what I need to compare the current time to the database variable:
if(startDate > now) {
var status = 'pre';
}
I've tried using setInterval as follows, but I can't access the updated (current time) outside of the setInterval function.
setInterval(function(){
now = moment(new Date()).format();
console.log('time1 ', now); // this works
}, 1000);
console.log('time2 ', now); // this doesn't
What am I doing wrong?

Try this..
var now = new Date();
setInterval(function(){
now = new Date();
console.log('time1 ', now.getHours()+":"+now.getMinutes()+":"+now.getSeconds());
}, 1000);
console.log('time2 ', now.getHours()+":"+now.getMinutes()+":"+now.getSeconds());
});

I ended up using react-interval https://github.com/nkbt/react-interval to accomplish this.

Related

Setting the milliseconds on Timeout based on given date time

I need help with setting my timeout for the function. I'm trying to set the timeout for a given date and time but my conversion of them to milliseconds is not working.
Here's my code. Please help.
<script>
var ref = firebase.database().ref().child("Message");
var newRef = ref.child("20161227125916539")
newRef.on('value',function(snap){
heading.innerText =snap.child("message").val();
});
ref.on("child_added",function(snap){
var date = snap.child("date").val();
var time = snap.child("time").val();
var type = snap.child("type").val();
var venue = snap.child("venue").val();
var route = snap.child("route").val();
var message = snap.child("message").val();
date = date + time;
date = date.getTime();
var now = new Date();
now = now.getTime();
set = date - now;
var explode = function(){
alert("Boom!");
};
setTimeout(explode, 2000);
});
</script>
You need to parse the date using new Date().
As you said, the value of date is "2016-12-27" and the value of time is "15:30", so while concatenating them, you also need an extra space. Something like:
date = date + " " + time;
var someDate = new Date(date);
var now = new Date();
var diffInMillis = now - someDate
var explode = function(){
alert ("Boom!");
}
setTimeout(explode, diffInMillis);
dateobj=new Date(datestring);
timeinmilliseconds=dateobj.getTime();
//by the way, may check the browsers console if sth is not working:
datestring.getTime();// error:undefined function
Youre calling the getTime function on a string. You need to convert it into a time obj first. Be aware of the right String format. There are good resources online.
The better Way:
A timeout is killed when the browser is reloaded. Thats bad. It would be better to store the time, and regularily check if the time is reached. That would survive reloads, crashes, shutdowns etc:
function set(timestring){
localStorage.setItem("timer",new Date(timestring).getTime());//store timer
check();//start checking
}
function check(){
if(var await=localStorage.getItem("timer")){//if timer is set
var now=new Date().getTime()
if(await<=now){//time reached, or reached in the past
alert("Yay, timer finished");
}else{//not reached yet
console.log(await-now+" left");//log the time left
setTimeout(check,1000);//check again in a scond
}}
window.onload=check;// browser started, check for an existing timer
Use like this:
set("28-12-2016 12:30");

How to keep Date object static and avoid updating?

I'm a bit of a newbie so please bear with me. I've created a date object in javascript every time someone opens a new page. I want to save the time the user opened the page and create another date object exactly one day later to create a countdown timer showing time elapsed from date 1 to date 2.
To accomplish this, I tried subtracting the two dates using .getTime; I want to keep the second date static instead of one day ahead of the current time. Unfortunately, this is not happening even though I have confined d2 (Date 2) to a condition that only runs once and is stored in variable nextday. Here's my JS
$(function (){
localStorage.clear()
var ran = JSON.parse(localStorage.getItem('run'))
d1 = new Date()
var i = 0
if(!ran){
i+=1
d2 = new Date(d1)
nextday = d2.setHours(d1.getHours()+24)
console.log(i)
console.log(typeof(nextday))
localStorage.setItem('run',JSON.stringify('ran'))
localStorage.setItem('nextday',JSON.stringify(nextday))
}
console.log(localStorage)
nday = JSON.parse(localStorage.getItem('nextday'))
console.log(nday)
var seconds = (nday - d1.getTime())
console.log(seconds)
console.log(localStorage)
})
Your script is clearing local storage every time the page is loaded:
localStorage.clear()
This will prevent anything from being stored across runs. Remove it.
You're clearing your localStorage before you access your locally-stored data. Thus, your ran variable is always empty. Remove that one call to clear(), and everything should work fine.
$(function() {
// localStorage.clear() <= the offending code!
var ran = JSON.parse(localStorage.getItem('run'))
d1 = new Date()
var i = 0
if (!ran) {
i += 1
d2 = new Date(d1)
nextday = d2.setHours(d1.getHours() + 24)
console.log(i)
console.log(typeof(nextday))
localStorage.setItem('run', JSON.stringify('ran'))
localStorage.setItem('nextday', JSON.stringify(nextday))
}
console.log(localStorage)
nday = JSON.parse(localStorage.getItem('nextday'))
console.log(nday)
var seconds = (nday - d1.getTime())
console.log(seconds)
console.log(localStorage)
})

getting current time in different time zone using moment.js

I am trying to figure out how to get current time in different time zones but below method does not return anything
var timeUpdate = setInterval(function () {
var currentTime = moment().format()
var GMT_current_time = currentTime.tz("Europe/London").format("HH:mm DD MMM");
$("#GMT_display_time").text(GMT_current_time);
}, 1000);
The output of the format function is a string. The tz function works on a moment object.
moment().tz("Europe/London")
Returns current time with format.
moment.tz(moment(), 'Asia/Karachi').format('DD/MM/YYYY HH:mm')

Jquery set counter, but reset when function is called

Does anyone know what function would be best to use for the following scenario?
When a song starts playing, I want to start a 'stopwatch' that counts up in seconds.
At any point, i'd like to be able to call this variable, such as a button that you click that'll do alert(time) and reveal the count on the timer.
But, when i run a function reset-timer(); I'd like this all to reset and start counting again.
I was thinking settimeout or setinterval but not sure which is correct.
Thanks :)
Here is a basic concept to get you started:
http://jsfiddle.net/V29qK/1/
var startTime = new Date();
function SetTime(){
var curTime = new Date();
var seconds = Math.round((curTime - startTime) / 1000) + " second(s)";
document.getElementById("timer").innerHTML = seconds;
}
var interval = setInterval(SetTime, 1000);
function ResetTime(){
document.getElementById("timer").innerHTML = "0 second(s)";
startTime = new Date();
}
​
The logic is: Set a global variable to a new Date() to signify the Start Time. On an interval (or timeout), get the current new Date() and subtract the Start Time from it. This will give you the difference in milliseconds. You can then update whatever UI element you want with this data.
To "Reset" the timer, you simply set the Start Time to the current time with new Date()

how to update time regularly?

function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
return f_date;
}
<span class="foo"><script type="text/javascript">document.write(timeClock());</script></span>
alert(now); gives me the value every second but it is not updated in the html. How can I update the time on the html without refresh the page?
There are a number of mistakes in your code. Without the use of var infront of your variable declarations, you leak them into the global scope.
Also, the use of document.write is discouraged.
Here's how I would do it:
JavaScript:
function updateClock() {
var now = new Date(), // current date
months = ['January', 'February', '...']; // you get the idea
time = now.getHours() + ':' + now.getMinutes(), // again, you get the idea
// a cleaner way than string concatenation
date = [now.getDate(),
months[now.getMonth()],
now.getFullYear()].join(' ');
// set the content of the element with the ID time to the formatted string
document.getElementById('time').innerHTML = [date, time].join(' / ');
// call this function again in 1000ms
setTimeout(updateClock, 1000);
}
updateClock(); // initial call
HTML:
<div id="time"> </div>
setInterval(expression, timeout);
The function setTimeout is intended for a single timeout, so using setInterval would be a more appropriate option. SetInterval will run regularly without the additional lines that Ivo's answer has.
I would rewrite Ivo's answer as follows:
JavaScript:
function updateClock() {
// Ivo's content to create the date.
document.getElementById('time').innerHTML = [date, time].join(' / ')
}
setInterval(updateClock, 1000);
Try it out yourself! https://jsfiddle.net/avotre/rtuna4x7/2/
x = document.getElementsByTagName('SPAN').item(0);
x.innerHTML = f_date;
try putting this code block instead of return statement, i haven't test it but it will probably work
There may be something in timeago jQuery plugin you can hook into, but I haven't honestly tried...
http://timeago.yarp.com/
$('span.foo').html(f_date);
place this inside your timeclock() function
untested
function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
$('span.foo').html(f_date);
}
I'd use setInterval rather than setTimeout:
https://developer.mozilla.org/en/DOM/window.setInterval
I think your setTmeout function has the wrong variables, the first one should be a function not a string, that confused me for a bit. Basically you need to write to the span tag when you run the function.
I created a jQuery version in a fiddle to demonstrate what I mean. Didn't have your strMonth function but you get the idea. I also changed the alert to console.log but you can remove that line.
http://jsfiddle.net/5JWEV/
Straigt Javascript time format / update
1: create month converter func
2: create time func
3: create update func
4: create outPut func
// month converter from index / 0-11 values
function covertMonth(num){
let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
// look into index with num 0-11
let computedRes = months[num];
return computedRes;
}
// time func
function Time(){
// important to get new instant of the Date referrance
let date = new Date();
this.time = date.toLocaleTimeString();
this.year = date.getUTCFullYear();
this.day = date.getUTCDate();
this.month = date.getUTCMonth();
this.currentTime = date.toLocaleTimeString() + ' ' + covertMonth(this.month) + ' ' + this.day + ' ' + this.year;
return this.currentTime;
}
function timeOutPut(){
let where = document.getElementById('some-id');
where.textContent = Time(); // 1:21:39 AM Dec 17 2017
}
// run every 5secs
setInterval(timeOutPut, 5000);
I used #soloproper setInterval concept #Ivo Wetzel overall answer, my update is all about formatting the time as required. Reduced Programming Lines
<div id="liveClock"> </div>
$(document).ready(function () {
updateClock();
});
function updateClock() {
document.getElementById('liveClock').innerHTML = new Date().format("dd/MMMM/yyyy hh:mm:ss tt");
}
setInterval(updateClock, 1000);
function timeClock()
{
setTimeout("timeClock()", 1000);
now = new Date();
alert(now);
f_date = now.getDate()+" "+strMonth(now.getMonth())+" "+now.getFullYear()+" / "+timeFormat(now.getHours(), now.getMinutes());
document.getElementById("foo").innerHTML = f_date;
}
<span id="foo"></span>

Categories