How do I update time on multiple rows using javascript - javascript

I'm using the fromNow function from moment.js library to display time elapsed from a specific date/time (e.g. '16 hours ago'). I use this within a table on multiple rows within my web app.
This part works fine, but I need the time to count continuously and for several rows (50 - 60 and growing). How do I get the time to count continuously and efficiently? I say efficiently because, I've read that using interval may be a bad idea so I'm not sure and I need help understanding.
This is how I create a cell which holds the elapsed time:
newCell = row.insertCell(++cellIndex);
newText = document.createTextNode(moment(data.checkintime).fromNow());
newCell.appendChild(newText);

Assuming the code you posted is correct, you can save the updated time in a variable and update all the rows. In that way, it's the same time that will display for all the rows and that time would just have to be done in one time:
var updatedTime = moment(data.checkintime).fromNow();
newCell = row.insertCell(++cellIndex);
newText = document.createTextNode(updatedTime);
newCell.appendChild(newText);

If you want the timestamp to continuously update, look into a library such as TimeAgo.
With your current code, simply change the text node to match timaeago's syntax <abbr title='{timestamp}' class='timeago'> and add the following javascript to the bottom of your page
jQuery(document).ready(function() {
jQuery("abbr.timeago").timeago();
});
This will continuously update the timestamp ("a moment ago", "2 minutes ago"....) which I believe is what you're looking for

Related

synchronising the Time without reloading the page

I'm building a web app that uses the Time of the computer I found how I can get the hours and the minutes and I succeeded to update them to the UI but the minute field is not synchronised with the time of the computer I have to reload the page to see it updated with the new value, I don't know how to solve this problem I feel like it's a stupid question but really I'm struggling with it, it's my first app with JavaScript so forgive me :p
I tried the setInterval but it didn't work too any help please
here is my code:
HTML
<div class="headTime" >Time: <span class="Time"> 03:19</span></div>
Js
var hours=d.getHours();
var minutes=d.getMinutes();
var Time=" 03:19";
var newTime=Time.replace("03",hours);
var newTime=newTime.replace("19",minutes);
setInterval(function(){
document.querySelector(".Time").innerHTML=newTime;
},1000);
any better title for the question?
I feel it's not accurate
You need to get the date each time in callback passed to setInterval. I have added seconds also for test purpose.
You donot need to get the test of span and use replace() and then show. You could directly use Template Strings
`${hours}:${minutes}`
Tip for you is declare the element .Time in global scope and don't call querySelector every second
const span = document.querySelector(".Time");
setInterval(function(){
let date = new Date();
let hours = date.getHours();
let mins = date.getMinutes();
let seconds = date.getSeconds();
span.innerHTML= `${hours}:${mins}:${seconds}`;
},1000);
<div class="headTime" >Time: <span class="Time"> 03:19</span></div>
Note:If you are only showing the minutes no seconds you shouldn't call the function every second

How to add input from a prompt to the local time using only JavaScript?

I'm a software engineering student in an Intro to JavaScript course and I'm stuck on an assignment. Here's the assignment,
in a file named alarmTime.html, use prompt() to find out how long the user wishes to nap. Then, write a statement to the document telling the user what time her/his alarm should go off. Be sure the times are local for the user.
I'm stuck on adding the input to the user's local time. I don't really know what I'm doing wrong and I'm having difficulty understanding what to do because all I'm getting is what seems to be random numbers. Please take a look at my code and point me in the right direction.
var howLong = prompt("How long, in hours, do you want to nap for?", 1);
var parsedInput = parseFloat(howLong);
var today = new Date();
var currentTime = today.toLocaleTimeString();
var myHour = today.getHours(currentTime);
var alarm = today.setHours(myHour + parsedInput);
document.write(alarm);
The reason is because of this statement document.write(alarm);. setHours method in Date object updates the Date instance, and returns the Date in milliseconds. Therefore, you are printing the Date object as the number of milliseconds since January 1, 1970. To fix that, simply replace it with document.write(today);
The problem is var alarm = today.setHours(myHour + parsedInput);
instead try to set the variable as
var alarm = today.getHours();
or change document.write(alarm); to document.write(today);
Date.now() will give you current time (users local time). Add time from prompt and your good:
let napTime = prompt('how many minutes do you want to nap?');
let alarmTime = new Date(Date.now()+napTime*60000);
//if you want to get HOURS instead of minutes
//let alarmTime = new Date(Date.now()+napTime*3600000);
//print it out. toLocale...() functions return local FORMAT of the datetime,
//they dont deal with timezones
document.write('set alarm to '+alarmTime.toLocaleTimeString('en-US'));
console.log(alarmTime);

How do I go about creating an event every hour and everyday?

I was wondering on to have an event every hour on every day in the AgendayDay view. I customized the timeslots to be an hour long. I will be filling the title/description with values from the database. I seen some questions answered for recurring events every monday for an example.
EDIT: I get the recurring event every monday as an example. I'm asking how do you create a different event for every HOUR without creating an event manually.
Something like this but for everyday. Of course, not every event will have the same value.
for(timeIncrement = 0; timeIncrement < 24; timeIncrement++){
$scope.events.push({
title: 'Rooms Available [' + 11 + ']',
start: new Date(yearClicked, monthClicked, dayClicked, timeIncrement)
});
}
Is what I came up with. This is inside a if statement when an available date has been clicked.

How to compare datetime in javascript

I have been trying to get the code to work for more then 2 hours, then I tried this site, well there is alot of code here! I have used each of them. Some are in jQuery while some were pure JavaScript.
Here is two of the code that I have tried:
First code: This code was caught from this link: https://stackoverflow.com/a/2725097/1762944
var dateTimeStr = "17:10:03";
var user_time = DateTime.Parse( dateTimeStr );
var time_now = DateTime.Now;
if( time_now > user_time )
{
// your code...
}
Second code: This one is jQuery. It worked for the asker, and was marked as answer too. It works I have checked the fiddle provided by him! But when I tried the code, it didn't work either. Here:
function time_until() {
currentTime = Math.floor(jQuery.now() / 1000);
seconds = eventTime - currentTime;
if(second == 0){
//Stop voting
}
days = Math.floor(seconds / (60 * 60 * 24));
$('#time').html('seconds ' + seconds + '<br/>days ' + days);
}
I have tried to edit them both. But they don't work.
Reason why they work: The reason behind this all, is that what I want to do is,
I have a database table which is storing the time for users. I mean when they made an activity such like posting status updates!
I have created a timestamp. Which shows perfectly like this: few seconds ago.
Now what I want is, to update the time to 1 minute ago without reloading the page, like Facebook does. Or whatever the time is, to get updated to the next minute or hour or corresponding.
What I have tried is almost next to everything. But I guess the only issue with my codes is that when I place the DateTime.Now value from Database in it, it shows an error. The error is hidden so I have created an else statement like this:
if(seconds < 60) {
$("#jstime").html(seconds + "seconds..");
// else if minutes, if hours they are all written..and then an else
} else {
$("#jstime").html("Again an error, try again bud");
}
I have a setInterval which keeps on updating the id with the error text.
Here is the code that I am using.
<span id="timeval" title="#timeStamp">#TimeStamp</span></div>
<input type="hidden" id="time" value="9/23/2013 8:10:40 PM" />
<span>Real time: #TimeStamp</span><br>
<span id="update">Updated time: no update till now;</span><br>
<span id="jstime">Time</span>
The timeval is the real time that is being shown to the users, input is the time from where I get the value of the time on each post, the next span just shows the time to me, I mean I used this to check what was the time when the page was loaded, update is the span to show the updated time, jstime can also be used to show the updated time.
The problem is that you stored currentTime in the function you call every n seconds. As it gets looped it will everytime create a new current time.
Make it a global variable so you can loop through the function without creating the time new and use the old time instead.
Please go to link on stackoverflow and see my answer on how can we compare two dates along with the time in Javascript.

Multiple javascript timeouts - problem with live data fetching

I am building a real-time system which (with a use of websockets) updates a table with live data of different frequencies (can be 3 times per second, can be once every 2 seconds - dependant on the type of data).
I am currently struggling to find a way of letting the user know when a particular field has not been updated in the last 5 seconds. That is, if no new data is fetched, I shouldn't keep the old value there, but rather change it to '--' or something similar.
After a long way to the javascript, final function which updates fields looks like that (extremely simplified):
function changeValue(data){
var fieldId= data.fieldId;
var value = Math.round(data.value);
$('span#'+fieldId).text(value);
}
This function gets called each time a field needs to be changed. I've got between 2 and 40 different fields (dependant on the user) that are changed.
What is the best way of setting timers in order to change the values of the fields to '--' every 5 seconds, if no update has been made?
I would be really grateful for some tips,
Thanks,
Karol.
Since you want to indicate timeout on a per-field basis, you have two obvious options:
Have a global interval timer that ticks over fairly frequently and looks through all of your fields for a timeout.
Have independent timers for each field which just deal with that field.
I think on balance I prefer (1) to (2), because we're only dealing with one interval timer then and it makes the housekeeping simpler.
Since IDs in documents must be unique, we can use your field ID values as a key in a hash (an object) to store last updated times. This is kind of a spin on the previous answer but works on a per-field basis. So here's how we'd set those last updated times:
var lastUpdatedTimes = {};
function changeValue(data){
var fieldId= data.fieldId;
var value = Math.round(data.value);
$('span#'+fieldId).text(value);
lastUpdatedTimes[fieldId] = new Date().getTime();
}
Then you set up an interval timer to check each of them.
function checkFieldsForTimeout(){
var now = new Date.getTime();
// For each ID in lastUpdatedTimes, see if 'now minus
// last updated' is > 5000 and is so, set the field
// text to '--' and remove that entry from the last
// updated list with "delete lastUpdatedTimes[itemId]".
}
Should a timed-out field spring back to life, the "--" will be replaced by some real text again.
By deleting the last updated time from "lastUpdatedTimes" whenever we put "--" into a field, we make sure that the interval timer isn't wasting time processing fields that have already been timed out.
This answer was extended to handling multiple fields after the comment by #Andrew (please see also his answer).
Introduce a property updatedTime, which holds the last time the data was updated, in each data. A periodic timer checks updatedTime for all data and updates the text field if appropriate. The check has to be twice as often as the detection period. Your function changeValue() updates updatedTime and the text field.
function checkData() {
var now = new Date.getTime();
for "each data" {
if (now - data.updatedTime >= 5000) {
var fieldId = data.fieldId;
$('span#'+fieldId).text('--');
}
}
}
function changeValue(data) {
var fieldId = data.fieldId;
var value = Math.round(data.value);
$('span#'+fieldId).text(value);
data.updatedTime = new Date.getTime();
}
// Install periodic timer to check last updates:
setInterval(checkData, 5000 / 2); // interval = half the required detection period

Categories

Resources