I am making an app displaying the current system time but I want to get the time my page started running so I can calculate and display the time that my page is up and running. I am using angularjs and currently has no idea on how can I get this. I have my code on getting the current system time like this
Current time is:
<span my-current-time="format1"></span>
<span my-current-time="format"></span> :
<span my-current-time="format3"></span> :
<span my-current-time="format4"></span>
<span my-current-time="format5"></span>
with this script
$scope.format1 = 'M/d/yy ';
$scope.format = 'h';
$scope.format3 = 'mm';
$scope.format4 = 'ss';
$scope.format5 = 'a';
$scope.format2 = 'Z ';
and a directive like this
.directive("myCurrentTime", function(dateFilter) {
return function(scope, element, attrs) {
var format;
scope.$watch(attrs.myCurrentTime, function(value) {
format = value;
updateTime();
});
function updateTime() {
var dt = dateFilter(new Date(), format );
element.text(dt);
}
function updateLater() {
setTimeout(function() {
updateTime(); // update DOM
updateLater(); // schedule another update
}, 1000);
}
updateLater();
}
});
I just want to display the total hours my page is currently running
first save the page load value... $scope.pageLoad = new Date()
and then use a filter to display that value
<p>running since : {{pageLoan | timespan}}</p>
and define timespan filter
angular.filter(timespan, function(time){
var now = new Date();
return (now - time) / 1000;
});
Related
I recently started working on a Work Day Schedule project that requires me to use jQuery, HTML and Day.js. This project requires that I display a clock at the top of the page, text areas that can be written in and saved to local storage (this text stays even when page is reloaded) and the color of each time block is based on whether it is past(gray), present (red), or future (green).
I have displayed the clock and figured out how to keep text saved in the text area but I cannot figured out how to keep the time blocks appropriately colored based on what time it is.
This is my javascript. The documentation I found to help was sadly written in moment.js and I'm wondering how I would convert this to Day.js to meet the project requirements.
var dateTime = $('#dateTime');
var saveBtn = document.querySelector(".saveBtn");
var currentHour = moment().hour();
function printDateTime() {
var date = moment().format("dddd, MMM Do YYYY")
dateTime.text(date);
}
function hourTracker() {
$('.timeSchedule').each(function () {
var schedulehHour = $(this).attr("id").split("time")[1];
console.log("currentHour " + currentHour)
console.log("schedulehHour " + schedulehHour)
if (schedulehHour < currentHour) {
$(this).addClass("past");
}
else if (schedulehHour == currentHour) {
$(this).addClass("present");
}
else {
$(this).addClass("future");
}
})
}
$(".saveBtn").on("click", function () {
var value = $(this).siblings(".description").val();
var time = $(this).parent().attr("id");
localStorage.setItem(time, value);
})
$("#time08 .description").val(localStorage.getItem("time08"));
$("#time09 .description").val(localStorage.getItem("time09"));
$("#time10 .description").val(localStorage.getItem("time10"));
$("#time11 .description").val(localStorage.getItem("time11"));
$("#time12 .description").val(localStorage.getItem("time12"));
$("#time13 .description").val(localStorage.getItem("time13"));
$("#time14 .description").val(localStorage.getItem("time14"));
$("#time15 .description").val(localStorage.getItem("time15"));
$("#time16 .description").val(localStorage.getItem("time16"));
$("#time17 .description").val(localStorage.getItem("time17"));
printDateTime();
hourTracker();
I tried writing in moment.js but needs to be in day.js.
I'm creating a website thats going to work like an online advent calendar; I want to be able to make sure that a link wont open until the correct day. Heres what I have so far:
<area shape="rect" coords="0,0,90,150" href="https://www.youtube.com/watch?v=dQw4w9WgXcQ" alt="1" target="_blank" onClick="return canOpen(this)">
<script>
function canOpen(isTrue) {
var isOpen = new Date("Dec "+isTrue+", 2020 00:00:00").getTime();
var currentTime = new Date().getTime();
var timeDifference = isOpen - currentTime;
if (timeDifference > 0) {
<! Go to link>
}
else {
<! Show popup "You can't open this yet!>
}
}
</script>
How could I make it so that you can go to the link if it is past the date in question, and how would I get the value of alt out of the link and into the script?
Thanks for any help.
You can use Element.getAttribute() to get attribute alt as event date for check in script.
Then check if the current date passed event date, redirect by change site's location, or do anything else you like otherwise, if the element has redirect as default behavior (like a tag), you will need return false; to prevent default behavior.
function canOpen(element) {
var isOpen = new Date("Dec "+element.getAttribute("alt")+", 2020 00:00:00").getTime();
var currentTime = new Date().getTime();
var timeDifference = isOpen - currentTime;
if (timeDifference > 0) {
window.location.href = element.getAttribute("href");
} else {
alert("Not yet!");
// return false; // for `a` tag
}
}
I created two functions, one to set the date, and one to check if the link can open. If the release date has passed, the href of the link changes from "#" to the Youtube link. The date updates every second with setInterval.
Example on JSFiddle
Also, did I just get RickRolled?
<a id="premiere-link" href="#">Youtube Link</a>
<script>
// setInterval(canOpen, 1000);
let month, day, year, time;
const link = document.getElementById('premiere-link');
setDate(); //set date immediatly on page load
setInterval(setDate, 1000); //update date every second
function setDate() {
var dateObj = new Date();
month = dateObj.getUTCMonth() + 1; //months from 1-12
day = dateObj.getUTCDate();
year = dateObj.getUTCFullYear();
time = dateObj.getTime();
}
function canOpen(month, day){
//set month and day for release
if (month >= 11 && day >= 1) {
alert('You just got RickRolled')
link.setAttribute('href', 'https://www.youtube.com/watch?v=dQw4w9WgXcQ');
} else {
link.setAttribute('href', '#');
alert('You have to wait to get RickRolled')
}
}
link.onclick = () => {canOpen(month, day)};
</script>
I'm having this div element that shows the time past since it got created. However it doesn't get updated and always remains on few seconds ago. It looks like this
var newMsg= "<div id="chat-time">'+ moment().fromNow()+'</div>";
$("#chat-list").html( newMsg);
How can I update this text. I know I can do it with sentInterval but I can't figure out how to do it properly.It just prints out seconds! I'm using this for a chatroom. So each message will have a timestamp in the formatof momentjs.fromNow().
Does setting timer for all these message create a problem? I'd appreciate a hint.
EDIT:I'm using this code as mentioned in below but it's not showing anything:
<div id="chat-time"></div>
var messageTimeStamp = new Date();
setInterval(function(){
var time = moment(messageTimeStamp).fromNow();
$("#chat-time").html(time);
}, 1000);
To make this work you need the element in the dom and the setInterval running without being included in any string concatenation
HTML
<div id="chat-time"></div>
JS
var $chatTime = $('#chat-time').text(moment().fromNow());
setInterval(function(){
var time = moment().fromNow();
$chatTime.txt( time );
}, 1000);
UPDATE 2
Given that you're using socket.io, you'd do something like this (demo: http://plnkr.co/edit/QuaMV6x1vNB0kYPaU6i1?p=preview):
// The messages the user can currently see.
var messages = [];
// You have something like this in your code, presumably.
socket.on('new message', function(data) {
addChatMessage(data);
});
function addChatMessage(data) {
// First add the message to the dome, with a unique id for the timestamp text.
var messageElementId = 'chat-message-' + data.messageId;
$("#chat-list").prepend($("<div>" + data.message + "<i> (sent: <span id='" + messageElementId + "'>just now</span>)</i></div>"));
// When you no longer display that message in the DOM it from clear this array. I'd render the DOM based on this list if I were you.
messages.push({
messageElementId: messageElementId,
timestamp: data.timestamp
});
}
// By updating all the messages at once you don't have memory leaks.
setInterval(function() {
messages.forEach(function(message) {
var time = moment(message.timestamp).fromNow();
$("#" + message.messageElementId).text(time);
});
}, 1000);
UPDATE 1
Given this is your code:
var newMsg= "<div id="chat-time">'+ moment().fromNow()+'</div>";
$("#chat-list").html(newMsg);
You would do this, instead:
var messageTimeStamp = new Date(); // You need to grab this from somewhere.
setInterval(function(){
var time = moment(messageTimeStamp).fromNow();
$("#chat-list").html(time);
}, 1000);
You need to use moment(TIMESTAMP_OF_MESSAGE) not moment() and do something like this:
$(function(){
$("body").append($('<div id="chat-time"></div>'));
var messageTimeStamp = new Date();
var i = 0;
setInterval(function(){
var time = moment(messageTimeStamp).fromNow();
$("#chat-time").html('moment().from(messageTimeStamp): ' + time + '; setInterval calls made ' + i++);
}, 1000);
});
Here's a demo.
http://plnkr.co/edit/QuaMV6x1vNB0kYPaU6i1?p=preview
I dont see any problem using setInterval (). AngularJS wrapper setInterval on $interval service module . Check out these urls: interval Angular and Wrapper SetInterval
function ShowTime() {
var dt = new Date();
document.getElementById("lblTime").innerHTML = dt.toLocaleTimeString();
window.setTimeout("ShowTime()", 1000); // Here 1000(milliseconds) means one 1 Sec
}
this code to displays time in a label but it always shows am only?
what is the way to display am pm correctly according to time (ist+5.30).
or is there any other way to display time without refreshing page
your current time might be AM so its showing as AM. change your system time manually to PM and then check.
fiddle:
http://jsfiddle.net/Bpvpa/1/
html:
<div id="lblTime"></div>
javascript:
function ShowTime() {
document.getElementById("lblTime").innerHTML = new Date().toLocaleTimeString();
}
setInterval(ShowTime, 1000); // Here 1000(milliseconds) means one 1 Sec
I've got an existing single page web application of which I can't change the code. Some users complain that the application is not performing very well.
I would like to monitor the loading time in this way:
Record the time stamp of a click on the page
Record the time stamp of when the rendering of the page has been completed, after ajax requests and some other javascript magic has been done
Calculate the difference between the two time stamps and post it back to the server.
I can easily do step 1 and 3 with jQuery, however I'm not sure what's the best way to approach step 2?
As this seems to be a quite obvious scenario, is there a standard tool set to perform this kind of monitoring?
This helps:
function onLoad() {
var now = new Date().getTime();
var page_load_time = now - performance.timing.navigationStart;
console.log("User-perceived page loading time: " + page_load_time);
}
You could use the global ajaxStop event jQuery offers.
var start = +(new Date());
$(document).ajaxStop(function() {
var diff = +(new Date()) - start;
// do logging
});
This won't include the code executed after the last AJAX call, but if things happening before the last call contain the expected bottleneck, then this will be quite useful.
this can be achieved in following way...
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="jquery.min.js"></script>
<script type="text/javascript">
var startTime, endTime, timeDifference;
function doIt() {
var startTime = new Date().getTime();
$.ajax({
type: 'post',
url: 'a.php',
success: function (resp) {
endTime = new Date().getTime();
timeDifference = endTime - startTime; //Time Difference is stored in milliseconds
}
})
}
</script>
</head>
<body>
<button style="position: absolute; top:60px" onclick="doIt()">start</button>
</body>
</html>
It's not a perfect solution, however the following code is working. It start the timer when a user clicks. The checkHTML function monitors the changes in the page content.
var timeLogging = new Array();
var timeStart;
$(document).click(function() {
initLogEvent();
});
function initLogEvent() {
caption = $(".v-captiontext:first").text();
timeStart = +(new Date());
timeLogging.push(new Array(0,0));
timeLogging[timeLogging.length - 1][0] = timeStart;
}
initLogEvent();
// Start a timer to check the changes in html
window.setInterval(checkHtml, 250);
// Start a timer to create the reports
window.setInterval(sendReport, 1000);
var html;
function checkHtml() {
current = $("body").html();
if (current != html) {
html = current;
var diff = +(new Date()) - timeStart;
timeLogging[timeLogging.length - 1][1] = diff;
}
}
function sendReport() {
if (timeLogging.length > 3) {
console.log(timeLogging);
// Do additional stuff with the collected data
for (i = 0; i <= timeLogging.length; i++) {
timeLogging.shift();
}
}
}
Are you keeping all you application's markup in the page, even when it is hidden? If so you are probably choking the browser's memory. I recommend learning to offload your markup in localStorage like Bing and Google pioneers a few years ago. I wrote a blog about it the day I discovered the technique and I have used it ever since.
http://love2dev.com/#!article/Use-Local-Storage-to-Make-Your-Single-Page-Web-Application-Rock