Detect Five Minute Mark - javascript

We use a graphing system that uses SNMP to retrieve data to graph with on every five minute mark. For example, 12:00, 12:05, 12:10, and so on. We retrieve the graph as an image. The problem is that the browser likes to use the cached image, and we cannot get a new image until we delete the cache. What I am trying to do is generate a random tag to append to the image that makes it unique, therefore not using the cached image. We were able to generate a random tag every time the image was retrieved, but this led to a lot of server utilization from all the requests and slower response times. What I am attempting to do now is generate a new tag ONLY if:
a) it has been greater than four minutes (5+) since the user retrieved an image (because a five minute mark would have had to pass),
b) it has been less than five minutes since an image was retrieved, but a five minute mark has passed since the last time an image was retrieved. For example, a if a person retrieves an image at 12:04, he or she won't be able to get a new one until five minutes later with the first test, but the second test will recognize that 12:05 passed if he or she attempts to retrieve an image at 12:06.
What I tried to do was use a cookie and set the cookie to the new tag every time a new tag was generated. On page load it would load RandomTag variable with the value of the cookie. Onclick it would be determined if five minutes has passed since the time in the RandomTag variable or if a five minute mark has past since the last generation of a tag, generate a new tag if it has, and set cookie with new tag; otherwise the tag would go unchanged.
Could anyone check this and see if there are any problems? I tried this code, and it made my page hang. I don't know what I am missing. Also, if you have a simpler way to do this, please let me know.
Here is an example of my code:
<body onload="checkCookie()">
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function checkCookie() {
randomTag = getCookie("timeTag");
}
function tagGet() {
timeNow = new Date().getTime();
timeDif = timeNow - randomTag;
minNow = timeNow.getMinutes();
minLast = randomTag.getMinutes();
minDif = minNow - minLast;
if (timeDif > 29999) { //If 5+ minutes have passed
randomTag = timeNow;
setCookie("timeTag", timeNow, 365);
}
else if (timeDif < 30000) { //If less than 5 minutes have passed
if (minDif > 0) { //If at least 1 minute has passed since last random tag generation
for (y = 0; y < minDif; y++) { //Check to see if a five minute mark has passed by decrementing the current minute mark and comparing it to a five minute mark
for (z = 0; z < 60; z += 5) { //Increment by five minute marks for comparison ... 0, 5, 10, etc
if (minNow == z) { //If the minute mark now matches a five minute mark
randomTag = timeNow;
setCookie("timeTag", timeNow, 365);
}
minNow--; //Decrement minute mark now for comparing next minute mark
}
}
}
}
}
# //This is generic

Set a global variable lastImage and set that to Date() when an image is requested.
Then only retrieve a new image if Date() >= lastImage + (5 * 60 * 1000).
And you can use Date() at the end of the url for the unique identifier to avoid caching.

Ok. I found a VERY simple solution to this. Basically I will just set my variable to equal the last five minute mark by rounding the current time down to the last five minute mark! Silly me. The answer was here, except I subtracted 2.5 instead of added 2.5 since I want to find the last five minute mark: Javascript: Round Time UP nearest 5 minutes

Related

How to automatically do an AJAX request for PHP script every day at certain time?

I tried to write a code that would everyday at 23:00 make an AJAX request to this URL { url: "addCredits.php" }. At this URL there is SQL code for adding +5 to the "Credit" column by using PHP. I want every user to receive +5 in their "Credit" column everyday.
I tried running the code below, but at 23:00, the user did not receive any credit.
<script>
function startTime() {
// set time variables h=hour, m=minute, s=second
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
//check if 0's have to be added for better appearance. no logical use!
m = checkTime(m);
s = checkTime(s);
//display current time on the element with id="txt"
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
//check if its 23:00:00 ... if so call addCredits.php
if(h == 23 && m == 00 && s == 00) {
$.ajax({url: "addCredits.php"});
}
//restart this function every second to update the clock
var t = setTimeout(startTime, 1000);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
I see a couple of problems here.
Are you sure your users actually had this page and running at 23:00:00? It won't work if the page isn't open, obviously.
getHours (et al) give the time in the user's local time zone. Users in different time zones will have this condition true at different times.
The condition you're using -- h == 23 && m == 00 && s == 00 -- will only be true if the timer fires between 23:00:00 and 23:00:01. Since you're using a 1000 millisecond timer, and JS timers aren't guaranteed to fire on the exact requested interval, it's possible that some users will end up "skipping" the condition if the timer fires at, say, 22:59:59.99 and 23:00:01.00.
Most importantly, though: Using client-side logic for this is completely insecure. Any user can request addCredits.php as many times as they want, whenever they want; the fact that it's normally requested through this Javascript won't stop them from running it other ways. If you want to give your users credits periodically, use a server-side scheduled task to do it.

Timer is resetting on refresh how to avoid that?

this is my java-script code which is resetting on refreshing how to avoid that
<script>
//define your time in second
var c=120;
var t;
timedCount();
function timedCount()
{
var hours = parseInt( c / 3600 ) % 24;
var minutes = parseInt( c / 60 ) % 60;
var seconds = c % 60;
var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
document.getElementById("timer").innerHTML=result;
if(c == 0 )
{
//setConfirmUnload(false);
//$("#quiz_form").submit();
window.location="result.php?td=$tid";
}
c = c - 1;
t = setTimeout(function()
{
timedCount()
},
1000);
}
</script>
Whenever a page is readloaded, the entire context of the old page is destroyed and an entirely new context is created. You can't keep a timer from one page load running on the next page load.
If you need to save some state from one page load to the next and then in the next page load examine that state and decide exactly how to set up the initial page to match what was previously going on, then you can save state between page loads in either HTML5 local storage or in a cookie.
The other possibility is to NOT reload your page and instead update the contents of the page dynamically using ajax and javascript. That way your existing timer would just keep running because there would be no page reload at all.
If all you're trying to do with your timer is show how much time is left in some countdown, you can set the countdown zero time into HTML5 local storage and when the reloaded page loads, it can check the time set in local storage and start the countdown timer to match the time it was previously set for.
Use cookie, or if HTML5 then local/session storage to save state.
HTML
Save Current Time |
Retrieve Saved Time
<div id="result"></div>
JAVASCRIPT
function SaveTime(){
var date = new Date();
var timeObj = { sec:date.getSeconds(), min:date.getMinutes(), hr:date.getHours() };
localStorage.setItem("timeObj", JSON.stringify(timeObj));
$('#result').append(JSON.stringify(timeObj)+' -- > Saved<br />' );
}
function retrieveTime(){
var timeObj = JSON.parse(localStorage.getItem("timeObj"));
//You have the time with you now
//You have the time with you now
$('#result').append(timeObj.hr+':'+timeObj.min+':'+timeObj.sec+' --> Retrieved<br />');
}
Its just a basic example to save timer in local storage on click. Modify it and call the javascript function in timer regularly.

using the time as a dynamic variable to compare values

I am working on programming a page in JS that grabs calendar data from an outside source, imports it into a multidimensional array and uses it to display who is currently working along with their photo, phone number, etc.
Right now I have it set up so that the page reloads every 15 minutes. I'd prefer to have this all done dynamically so that when, say, the clock strikes 5pm the page knows to update without having to wait until the 15 minute refresh is triggered.
All of the work times are pulled from the other calendar in 24 hour format (so 5pm is 1700).
Here's how I'm generating the current time to compare with the start/end times in the calendar:
//Get the current date and time
var dateTime = new Date();
var month = dateTime.getMonth() + 1;
var day = dateTime.getDate();
var dayOfWeek = dateTime.getDay();
var year = dateTime.getYear() + 1900;
//converting hours and minutes to strings to form the 24h time
var hours = dateTime.getHours().toString();
if (hours.length === 1) {
var hours = '0' + hours
};
var minutes = dateTime.getMinutes().toString();
if (minutes.length === 1) {
var minutes = '0' + minutes
};
var time = hours + minutes;
//convert the 24h time into a number to read from later
var timeNumber = parseInt(time);
I then use if statements to compare the start/end times from the imported schedule with timeNumber to determine who is currently working and push that to an array that is eventually displayed on the page with this code:
//figure out who is currently working and put them in the workingNow array
var workingNow = [];
for (i = 0; i < workingToday.length; i++){
//convert time strings to numbers to compare
var startTime = parseInt(workingToday[i][7]);
var endTime = parseInt(workingToday[i][8]);
//compare start and end times with the current time and add those who are working to the new list
if(startTime < timeNumber && timeNumber < endTime){
workingNow.push(workingToday[i]);
}
};
I guess I have just been trying to figure out how to make this comparison of the data in an array with the current time something that is dynamic. Is this possible or would I need to go about this in a completely different way from the ground up?
You should have a look at momentjs. This is a really good library to handle all sort of time and date manipulation.
http://momentjs.com/

Cannot print message according to time

I've three different times, two of them are in string forms (time1 and time2) and one from system date currDate. Next step according to the one of two above times I want to print messages when the system date reaches one of them. For this I've function callEachMinute that calls each minute to get system time (but here in code I did not include the whole procedure). Here is the current status of the code:
Script:
function callEachMinute() {
var currDate = new Date();
var time_1 = '8:30';
var time_2 = '23:00';
timeComparison(currDate, time_1, time_2)
}
function timeComparison(currTime, time1, time2) {
// Time 1 formatting
var t1 = new Date();
var parts1 = time1.split(":");
t1.setHours(parts1[0],parts1[1]);
// Iftor-Time formatting
var t2 = new Date();
var parts2 = timeI.split(":");
t2.setHours(parts2[0],parts2[1]);
/* Notification procedure */
if (currTime == t1) {
// Message for Time1
alert("Time 1 is reached");
}
if (currTime == t2) {
// Message for Time2
alert("Time 2 is reached");
}
}
Problem:
When the system time is reached one of times (time1 or time2) nothing happens. Any solution for this problem?
There are a few things that could be problematic here.
You set up a Date object then want to compare it to currTime:
if (currTime == t1) {
unfortunatley Javascript's == operator when applied to objects compares two objects to see if they are references to the same object, so even if currTime and t1 contained exactly the same time this check would evaluate to false since they are different instances. You could do this by converting to a string:
if (currTime.toString() == t1.toString) {
which would work if the string representations for each data work out the same.
However, a more straight forward approach might be to tackle this the other way around - extract the hours and minutes from currTime, build a string and compare that to your time strings. Something like:
// in timecomparison function
var hrs = currTime.getHours();
var mins = currTime.getMinutes();
var now = hrs+":"+mins
// now do comparisons
if (now == time1 ) {
....
}
and so on.

Change an image every minute using the computer's clock to time the changes

I want to change an image every minute. When the computer's clock moves from 8:50 to 8:51 then to 8:52 all the way back to 8:49 I want my picture to change from 0001.jpg to 0002.jpg to 0003.jpg all the way to 1440.jpg.
Since I am going to be using the computer's clock, I am interested in using JavaScript. I am also just starting out, so full code (which would be awesome!) is probably not what I need. Instead, I am looking for a place to start and maybe a direction to go. Any resources online that you know of would also be helpful
compute how many seconds until the next minute starts, then using setTimeout begin rotating the pictures. Use setInterval to do so every 60000 milliseconds.
var seconds = 60 - new Date().getSeconds();
setTimeout(function(){
console.log('start');
setInterval(function(){
console.log ('iterate over pictures here');
}, 1000 * 60);
}, seconds * 1000);
You can read more about both functions here
You'll want to study up on setInterval().
The code would look something like this:
var counter = 1,
lastUpdate = (new Date()).getTime(),
img = document.getElementById('image'); // Assuming your HTML has an img tag
// with an id of "image"
// This function just pads your number with 0s
function pad(num) {
var padding = '',
i = 4 - num.toString().length;
while (i > 0) {
padding += '0';
i -= 1;
}
return padding + num;
}
// This function is what actually does the updating
function update() {
var now = (new Date()).getTime();
if (lastUpdate + 1000 <= now) {
lastUpdate = now;
img.src = pad(counter) + '.jpg'; // change the image
counter += 1; // increment the counter
if (counter > 1440) { // reset to 1 if we get to our last image
counter = 1;
}
}
}
// Run update every 10th of a second
setInterval(update, 100);
The Mozilla Developer Center site has lots of great JavaScript and DOM references. I would also suggest learning to use JSLint, it will help a lot in avoiding stupid syntax errors that will cause headaches. I would suggest reading Douglas Crockford's book JavaSript: The Good Parts and Stoyan Stefanov's Object-Oriented JavaScript they are both excellent books to learn JavaScript from.
Place the code below in the BODY of a page:
<img />
<script>
var start = new Date().getTime(),
i = 0,
//get the node of the image to change
img = document.getElementsByTagName('IMG')[0];
setInterval(function(){
//what time is now
var now = new Date().getTime();
if(now - start > 60000){
//initialize the counter
start = now;
//overlay with 0's -> substr(-4)
//rotate on 1440 with a modulo -> i++ % 1440
img.src = ('000' + (i++ % 1440 + 1)).substr(-4) + '.jpg';
}
}, 10000); //check every 10 sec
</script>
If you start with Javascript a good reference is MDC
If you want to do this tied to the computer clock. Use the setInterval with a delay less than a second (<1000) and check the actual time with Date(). This way you can make your changes according to the clock.

Categories

Resources