need javascript to automatically reload page when minute updates - javascript

I am using the following code in my website which displays the current time
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML =
h + ":" + m;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
i am also using the automatic refresher tag in my html which reloads page after every 60 seconds
<meta http-equiv="refresh" content="60">
what i want is whenever the time changes to next minute the page reloads
which means if current time is 14:05 and when it hits 14:06 the page reloads by reading this time change and NOT by 60 seconds interval from which the user opens the page.

You can set timeout looking at the clock, just get the actual seconds and wait til 60 to reload:
var date = new Date();
setTimeout(function(){
window.location.reload(1);
},(60 - date.getSeconds())*1000)
Just put that at the head inside a script tag

Try using this
setTimeout(function(){
window.location.reload(1);
}, 60000); // 60 sec
Source: How to reload page every 5 second?
or take a look at this too
setTimeout(function(){
var minutes = (new Date()).getMinutes()
if ( !minutes%15 ) location.reload(); // if minutes is a multiple of 15
},60000); // 60.000 milliseconds = 1 minute
Source: jQuery auto refresh page on clock time

Handling the local time using client side script is not recommended because the user's clock might be messed up and thus your system would turn out to be faulty.
So it is better you fetch time from your server using any server-side language like PHP
In PHP:
<?php
echo date("h:i");
?>
Now you can call this function using AJAX and you can easily handle your time.
var result=null;
function getDate(){
var result=$.ajax({
url: "script.php",
type: "POST",
success: function(data){
setTimeOut(function(){getDate();},60000);
}
}).responseText;
}

Related

Get page load time in angular

I am working on a angular project where I need to track the page loading time.
Is there any method in angular using which I can track page loading time.
Code that I tried:
var loadTime = window.performance.timing.domContentLoadedEventEnd - window.performance.timing.navigationStart; console.log('Page load time is ' + loadTime);
You can use setInterval combined with angular.element(document).ready().
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<script>var time = 0;
var stopwatch = setInterval(function() {
time = time + 0.001;
}, 1);
angular.element(document).ready(function() {
clearInterval(stopwatch);
document.getElementById("text").innerText = "It has taken " + time + " seconds for this page to load.";
});</script>
<span id="text"></span>

jQuery Cookies Function not Working in Chrome

I am facing a problem in a jQuery code. It's working in Safari and Firefox but is not working in the Chrome. Here is the explanation of the function below.
Once the user click on closebtn div, and then after refreshing the page, fade and form should not display for 24 hours. But just for that particular user who clicked on "closebtn".
Fade and Form should not work for next 24 hours on that particular ip address or computer or in that browser of that person's computer. Fade and Form can open if the webpage gets opened from any other computer.
Here is the code:
$(function(){
//var flag = Cookies.get('hideFormAndFade');// this returns value if set else undefined if cookie not found
var flag=$.cookie("hideFormAndFade")
alert(flag);
if(flag == false || flag==undefined){ // if cookie found and if cookie value is not true
setTimeout(function(){
$('.fade').show();
$('.closebtn').show();
$('.form').show();
},2000);
}
$('.closebtn').click(function(){
$('.fade').hide();
$('.form').hide();
var date = new Date();
var minutes = 30;
date.setTime(date.getTime() + (minutes * 60 * 1000));
$.cookie("hideFormAndFade", true , { expires: 1 });
//Cookies.set('y', "sd"); // 1 is 1 day
//Cookies.set('hideFormAndFade', true, { path: '/' , expires: 1 }); // 1 is 1 day
});
});
Please help with this functionality.

jQuery setinterval function change css

I want to make a function to change my background <header> every 5 seconds.
On the one hand I have an image that changes every X time, It is generated by a php file:
../bg.php
So I've done that I change the background-image with $("header").css().
Running the script like this:
(function($)
{
$(document).ready(function()
{
var $container = $("header");
$container.css("background-image", "url(bg.php)");
var refreshId = setInterval(function()
{
$container.css("background-image", "url(bg.php)");
}, 9000);
});
})(jQuery);
But does not change by itself.
This is just a guess, but there's a good chance that the browser is just caching the file. You could add cache control headers on the server, or else add a nonce parameter each time you change the background:
var counter = 1, refreshId = setInterval(function()
{
$container.css("background-image", "url(bg.php?_=" + counter++ + ")");
}, 9000);
It's probably a good idea to go ahead and set the cache headers properly anyway, just to avoid having client browsers needlessly cache the same image over and over again.
Maybe because your browser cache it. place a random number at the end of url:
$container.css("background-image", "url(bg.php?rnd=" + Math.random() + ")");
var refreshId = setInterval(function()
{
$container.css("background-image", "url(bg.php?rnd=" + Math.random() + ")");
}, 9000);
window.setInterval(function(){
/// call your function here
}, 5000);
You probably need to call location.reload(); as well.
Try to add query to bg.php
var d = new Date();
var n = d.getTime();
$container.css("background-image", "url(bg.php?" + n + ")");
the browser will not load the file with same name again
You're going to need to set the background-image to a different URL if you don't want to reload the entire page. However, you can attach a fragment (ex. http://example.com/index.php#fragment), or alternatively a query string (ex. http://example.com/index.php?querystring) to that URL .php file each time. If you are going to reset it every 5 seconds, a good method would be to append a new Date().getTime(); to the end of the image source URL, like this:
var currentDate = new Date();
$container.css("background-image", "url(bg.php#" + currentDate.getTime() + ")");
or even more succinctly/efficiently
$container.css("background-image", "url(bg.php#" + new Date().getTime() + ")");
You should end up with a background-image property of something like url(bg.php#1413320228120). This is good because the fragment won't affect where the browser looks for the image (still bg.php), but it'll consider it a different URL each time and load it again.
Your solution should look something like:
(function($)
{
$(document).ready(function()
{
var $container = $("header");
$container.css("background-image", "url(bg.php)");
var refreshId = setInterval(function()
{
$container.css("background-image", "url(bg.php)");
}, 9000);
});
})(jQuery);

JQuery progress bar pauses when browser tab is changed

I'm trying to display a progress bar on a html page using javascript. However,
when the browser tab containing the code becomes inactive, the progress bar stops updating,
being resumed when the tab is active again.
How can I prevent the browser from stopping/pausing the execution of javascript code when the window is inactive?
Although it may be irrelevant, here is the code:
Object.progressBar = function(){
$( "#question-progress-bar" ).progressbar({
value: false,
complete: function(event, ui) { ... }
});
var seconds = 15.0,
progressbar = $("#question-progress-bar"),
progressbarValue = progressbar.find(".ui-progressbar-value");
progressbarValue.css({
"background": '#c5b100',
"opacity" : '0.8'
})
var int = setInterval(function() {
var percent = (15-seconds)/15*100;
seconds=seconds-0.1;
progressbar.progressbar( "option", {
value: Math.ceil(percent)
});
$("#question-progress-bar-seconds").html((seconds).toFixed(1)+"s");
if (seconds <= 0.1) {
clearInterval(int);
}
}, 100);
}
Instead of using setInterval and assuming a certain amount of time has passed between calls (even when it's up front, setInterval has hit or miss accuracy) use the Date object to get a time when the bar starts, and compare that to the current time at each iteration.
<html>
<head>
<script>
function go()
{
var pb = new ProgressBar(5, "targ");
}
window.onload = go;
function ProgressBar(l, t)
{
var start = Date.now();
var length = l * 1000;
var targ = document.getElementById(t);
var it = window.setInterval(interval, 10);
function interval()
{
var p = 100 * (Date.now() - start) / length;
if(p > 100)
{
p = 100;
window.clearInterval(it);
alert("DONE"); // alternatively send an AJAX request here to alert the server
}
targ.value = (Math.round(p) + "%");
}
}
</script>
</head>
<body>
<input type="text" id="targ" />
</body>
</html>
I've made an example object, here, that immediately starts a countdown when instantiated and calls an alert and kills the interval timer when done. Alternatively an AJAX call, or any other sort of call can be done upon completion.
It should be noted that this will NOT complete the call if the browser stops Javascript all together. It will, however, complete it as soon as the tab has been given focus again if enough time has passed in the interim. There is no way for a website to alter this sort of browser behavior from the scripting side.
Hope that helps!

Combine ASP.net AJAX timer with javascript countdown

I am currently working on porting a vb.net winforms program over to a web based version, and one of the functions in the original program has be stumped.
In the original program, every 5 minutes, a form pops up for user input. There is also a label control on the main form which counts down to the next popup. This is accomplished with a single timer control with a 1 second duration. every tick, it decrements the countdown, and when the countdown reaches 0, it pops up the form and then resets. Simple enough, but in my web app, I can't afford to be doing a postback every second, so what I am attempting is to combine a javascript countdown widget with an AJAX timer. Essentially, what should happen is that when the page loads, the countdown begins decrementing from 300 seconds, and the AJAX timer begins with a duration of 300 seconds. My idea is that when the timer ticks, it will run my function, as well as reset the countdown to 300 seconds again.
My problem, is that I am not able to reset the countdown with the code that I have, and I know that I am doing something (likely very simple) wrong, but I don't know enough Java to know what.
If I hardcode the Timer var to 300, the countdown works, and the timer ticks (fires the additional functons), but the countdown just keeps counting down (into negative numbers). How do I reset the countdown variable from code behind?
Here is the countdown function
var Timer = <%= CountDown %>;
function updateClock() {
// Update Countdown
Timer -= 1;
var TimerMin = Math.floor(Timer / 60);
var TimerSec = Timer - (TimerMin * 60);
TimerSec = (TimerSec < 10 ? "0" : "") + TimerSec;
var TimerFormat = TimerMin + ":" + TimerSec;
// Update the countdown display
document.getElementById("javaCountdown").firstChild.nodeValue = TimerFormat
}
Here is the body code
<body onload="updateClock(); setInterval('updateClock()', 1000 )">
And the Code Behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Countdown = 300
End Sub
PProtected Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
Countdown = 300
'Additional Functions
End Sub
This solution uses jQuery.
<script>
var intervalSecond = null;
var interval5minutes = null;
$(document).ready(function() {
// enable both intervals
enableIntervals();
// onsubmit event for your form
$("#popupForm").submit(function() {
// hide the form again
$("#popupForm").css("display", "none");
// enable intervals again.
enableIntervals();
});
});
function enableIntervals() {
// every second interval
intervalSecond = setInterval(function() {
$("#updateMeEverySecond").html(new Date());
}, 1000);
// every 5 minutes interval
interval5minutes = setInterval(function() {
// display form and shut off the interval timers
$("#popupForm").css("display", "block");
clearInterval(intervalSecond);
clearInterval(interval5minutes);
}, 5 * 60 * 1000);
}
</script>
<div id="popupForm" style="display:none;">
<form>
<input type="text" />
</form>
</div>
<label id="updateMeEverySecond">Test</label>

Categories

Resources