How to make timer that can run on background also? - javascript

I am working on rails and written javascript code for displaying timer that starts from 00:00:00.
[NOTE: i have two button start and stop for starting the timer and stopping the timer]
function timer(){
var sec, min, hour;
sec=0;
min=0;
hrs=0;
sec++;
if(sec>=60){
min++;
sec=0;
}
if(min>=60){
hrs++;
min=0;
}
document.getElementById("hrs").innerHTML=hrs;
document.getElementById("min").innerHTML=min;
document.getElementById("sec").innerHTML=sec;
setTimeout(timer(), 1000);
}
Now this is working fine in my rails web application. But if I will redirect to another page and return to this page I am losing the timer value.
Here, I want the clock to be running continuously after page redirect also.
How to fix this?

get the timestamp... save it somewhere and pass it as a variable to the next page
var start=new Date().getTime();
to get the time passed
var currentMillisecondsPassed=new Date().getTime()-start;
convert this to hh:mm:ss.msec or whatever...
the next page needs just the start value and there are many ways to pass it..
php,js,get,post....and manymany more.
setTimeout() is also not precise for timers.
here is an example passing the value with querystring..
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>timer</title>
<script>
window.onload=function(){
var pt=window.location.search.split('=')[1],
e=document.body.childNodes,
t=e[0],
s=(pt*1||0),
interval,
ms2Time=function(a) {
var ms=parseInt((a%1000)/100),
s=parseInt((a/1000)%60),
m=parseInt((a/(1000*60))%60),
h=parseInt((a/(1000*60*60))%24);
return (h<10?'0'+h:h)+':'+(m<10?'0'+m:m)+':'+(s<10?'0'+s:s)+'.'+ms;
},
Start=function(){
s=new Date().getTime();
interval=window.setInterval(getcurrent,100);
},
Stop=function(){
window.clearInterval(interval);
s=0;
},
getcurrent=function(){
t.textContent=ms2Time(new Date().getTime()-s);
},
changepage=function(){
window.location='?start='+s;
};
e[1].addEventListener('click',Start,false);
e[2].addEventListener('click',Stop,false);
e[3].addEventListener('click',changepage,false);
if(pt&&pt!=0){
interval=window.setInterval(getcurrent,100);
}
}
</script>
</head>
<body><div id="timer"></div><button>start</button><button>stop</button><button>anotherpage</button></body>
</html>
as i said... you can store the start value anywhere ...so if you have any preferences ... just tell me and i can change the code for u.

Because you are redirecting, a java-script timer won't do. You should use system time instead. You can take some help from session variables while redirecting from the page, to save the time stamp when the timer started.

You can set the initial values for the variables sec, min, hour using session or cookies. And include this file in all the pages which you want the timer should run in background.
function timer(){
sec++;
if(sec>=60){
min++;
sec=0;
}
if(min>=60){
hrs++;
min=0;
}
setTimeout(timer(), 1000);
}
And add the values to the DOM only in the page which you are showing the timer.

Try to send default sec, min and hrs values from server, e.g. save them in coockie.

Related

How I can display a banner that changes every 10 seconds and respect the period while the page refreshes?

I am developing a builder of advertising campaigns on js and php that displays a banner every 10 seconds with setInterval function of javascript, but when the site refreshes the setInterval restarts. if you refresh the page in less than 10 seconds it will always display the same banner.
Is there a way to maintain a setInterval function in the server side, or something?
I'm trying this with javascript storing each second on a localStorage (HTML5) to continue in the same second when you refresh the page, but I think that is not the way to do it.
I hope someone will help me to jump this hurdle that has breaking my head. :)
You need to persist the state of the interval timer somewhere, either on the server or on the client. Local storage sounds like one option. Other options would be a cookie, a url parameter, or a form parameter if you are using HTTP post.
Is there a way to maintain a setInterval function in the server side, or something?
You say you're using PHP, so just use a PHP session to record when the last banner was loaded. If you get another call and the session time is <10 seconds ago then serve the same banner, otherwise serve a new one.
Yes, you'll still need a 10 second timer in JavaScript to trigger the banner to refresh, but you don't need all that stuff with localStorage -- it sounds like you're overthinking a really simple problem.
You can store your timer in a session which will only update every ten seconds
<?php
if (!isset($_SESSION)) {
session_start();
}
$time = time();
echo $time.'<br>';
$interval = 10; // ten seconds
if(!isset($_SESSION['timer']) || $_SESSION['timer'] == '') { // if the timer has not been started
$_SESSION['timer'] = $time; // sets the timer to start now
echo 'start timer = '.$_SESSION['timer'].'<br>';
} else { // the timer has already been started
echo 'timer = '.$_SESSION['timer'].'<br>';
if(($_SESSION['timer'] + $interval) < $time) {
// get new banner
echo 'get new banner<br>';
$_SESSION['timer'] = $time; // start the timer again
} else {
echo 'not yet';
}
}
?>
Try running this code and refresh the page every second... you will see "get new banner" only every ten seconds. Otherwise you will see "not yet".
You can put your code to get the new banner here `// get new banner'

How to create a javascript timer?

I want to start/display a timer on submit button event. I am using spring mvc. So on submit, it goes to the controller, performs some logic and gets redirected back to the original jsp page.The problem is the timer gets reset on page load when its redirected from controller.Once the timer is started, it shouldn't be reset until a stop timer button is clicked. How can i implement this functionality?I am using a jquery timer plugin, but its not quite working.I tried adding a counter=0 value, its not right either.
This is my code:
var counter=0;
function updatecounter(){
counter = 1;
Example1.init();
}
var Example1 = new (function() {
var $stopwatch,
incrementTime = 70,
currentTime = 0,
updateTimer = function() {
$stopwatch.html(formatTime(currentTime));
currentTime += incrementTime / 10;
};
this.init = function() {
$stopwatch = $('#stopwatch');
Example1.Timer = $.timer(updateTimer, incrementTime, true);
};
this.resetStopwatch = function() {
currentTime = 0;
this.Timer.stop().once();
};
if(counter!=0){
$(init);
}
});
HTML markup:
<h2><span id="stopwatch">00:00:00:00</span></h2>
<input type="submit" value="Run Script" name="Run Script" class="button"onclick='updatecounter();' />
<input type="submit" value="Stop Script" name="Stop Script" class="button" onclick='Example1.resetStopwatch();/>
I'm not going to try to create an entire application stack, so I'll keep this simple.
If you MUST redirect to the Spring Controller, then you're going to have to
Pass the start time from the page back to the controller
Pass that same start time from the controller back to the original page
Check for the start time when the page loads and
Start the timer
Add time to the timer equal to the difference between the start time reported from the server and now
So in pseudo-code:
if( startTime IS set ){
timer.start();
timer.setStartTime( startTime );
}
And this would assume that your timer simply calculates a difference from the start time to display a count.
However, the much better option would be for the page to NOT redirect to the server.
Just send off an AJAX request and let it come back whenever, and you can have your timer running the whole time.
This makes the most sense because the very nature of your question ("I need this thing to happen at the same time another thing is happening!") screams Asynchronous, which is the A in AJAX.
Try what this person recommends.
Session variables
Ok Finally i figured a way to fix it..On submit, I created a flag on server side and pass it to the jsp on page load. Based on the flag, it automatically starts the timer.Since its a quick process,( forward to controller and redirect back to jsp) the time delay is negligible.

Countdown does not work after using the PHP time string into javascript

I am creating time that i will use to make a countdown timer later. Its easy to create when only JavaScript or jQuery is my choice. But the problem comes when i get the PHP date time string and display it using jQuery. It does not dynamically update the time after using the PHP date and time string. Below is a little code of mine.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var value = $("#date_time").text();
function countdown(){
setTimeout(countdown, 1000);
var date = new Date(Date.parse(value));
$("#php_date_time").text(date);
}
countdown();
});
</script>
</head>
<body >
<div id="date_time"><?php echo Date("d-m-Y H:i:s");?></div>
<div id="php_date_time"> </div>
</body>
</html>
The code works perfectly fine if i do not pass PHP date time string to javascript Date() function as an argument. If starts working, i can make countdown myself.
var date = new Date(); // works fine without passing php date time string
var date = new Date(Date.parse(value)); // this does not work fine. Time does not update
Please help suggest what i need to do.
Thanks.
Since you want it to start from time that PHP gives you you need to change your javascript to use that time to set initial value and then change that each second. Now you're just updating with same value.
http://codepad.viper-7.com/sPVlEI
$(document).ready(function(){
var value = $("#date_time").text(); //get init value
var date = new Date(Date.parse(value)); //store initial time
setInterval(function countdown(){
$("#php_date_time").text(date); //set time
date = new Date(date.getTime() + 1000); //create new time from old + 1 sec
},1000); // will call countdown() function every second
});
The problem is as the server compiles your php date just once, your countdown function always uses the same date value. there is another issue that you have to consider which is your server time doesn't necessary match with client time. you'd better start your timer with client time. but if you want to start it based on your server time, try this and your problem is solved:
$(document).ready(function(){
var value = $("#date_time").text();
function countdown(date){
setTimeout(function(){
countdown(new Date(date.valueOf()+1000));
}, 1000);
$("#php_date_time").text(date);
}
countdown(new Date(Date.parse(value)));
});

Is it possible to store setTimeout function inside a localstorage?

Provided that I have the javascript code below.
var timeout = setTimeout(function(){
alert('this is executed after 5 seconds');
}, 5000);
localStorage.setItem('timeout_event', timeout);
I have checked the return value of the setTimeout function to be an id or something. If the user refreshes the page, how do I re-run the timeout event? Is it even possible?
Any help will do. Thank you in advance.
I have checked the return value of the setTimeout function to be an id or something.
Yes, it is a numeric id which you can pass to clearTimeout for cancelling a scheduled function run.
If the user refreshes the page, how do I re-run the timeout event?
Yes, when the page is unloaded all outstanding timeouts are aborted, so you'll need to restart the timeout on the new page.
Is it even possible?
Yes and no. You won't be able to run the function which you scheduled from the last page - all its context/scope would be lost - you need to create a new one, in the context of the new page.
But if you want to execute certain functionalities based on a timeout/interval across pages, you can do so by using DOM storage or similar. You would store the timestamp of the designated function run, and a flag whether it has already run. That way, you can check on following pages whether and when you need to re-schedule the function.
If you want your timeout function to be executed whenever the page is refreshed , you just add the function in window.onload
var timeout = setTimeout(function(){
alert('this is executed after 5 seconds');
}, 5000);
window.onload = timeout;
This works fine for me
If you want it to be executed for multiple times , then go for setInterval()
var timeout = setInterval(function(){
alert('this is executed for each second');
}, 1000);
window.onload = timeout;
It will be executed until you call clearInterval(timeout);
If you want multiple timeouts then you should do something like this
var timeout = setTimeout(function(){
alert('this is executed after 1 second');
}, 1000);
var timeout1 = setTimeout(function(){
alert('this is executed after 2 seconds');
}, 2000);
var timeout2 = setTimeout(function(){
alert('this is executed after 3 seconds');
}, 3000);
window.onload = timeout;timeout1;timeout2;
This is because setTimeout calculates the time as soon as the page is refreshed and this works fine for me
Thanks for the help guys.
I managed to find a way to solve the problem.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Testing</title>
<script type="text/javascript">
var timeout_time = 10;
var time_remaining = 0;
if(localStorage.getItem('timeout_time')==null){
run_timeout(timeout_time);
}
else{
run_timeout(localStorage.getItem('timeout_time'))
}
setInterval(function(){
time_remaining = localStorage.getItem('timeout_time');
if(time_remaining > 1 || time_remaining != null){
localStorage.setItem('timeout_time', time_remaining - 1);
}
}, 1000);
function run_timeout(time){
setTimeout(function(){
alert('executed on 10 seconds');
localStorage.removeItem('timeout_time');
}, time * 1000);
localStorage.setItem('timeout_time', time);
}
</script>
</head>
<body>
This is the test page.
</body>
</html>
I hope this can be useful for others.
Again, thank you all.

Suggest a way to update time every minute

I have a full ajax application. i am using the below code to update time every minute. But if i keep the browser open for >10 min the browser becomes non responsive/slow. Suggest a better code.
function tick()
{
var d = new Date();
var time = padNumber(d.getHours(),2)+':'+padNumber(d.getMinutes(),2);
$('#WeatherBoLfTime').html(' '+time);
t = setInterval('tick()',60000);
}
$(document).ready(function(){
tick();
})
The problem is that you're calling setInterval many times and never clearing any of them. So after a while you have lots of interval callbacks running at around the same time.
Change
t = setInterval('tick()',60000);
to
t = setTimeout(tick,60000);
When I first started out coding JavaScript I took down a Lycos web server with AJAX calls because I made the same mistake :-)
Note that since you're displaying the actual time, you should use a much shorter timer than 1 minute. If I land on your webpage at 13:42:30, the time will not be updated until ~13:43:30. To keep it in sync with the machine's time, you would probably want to set the timer for 1000.
setInterval() sets an interval. You only need to set it up once, it will get called every 60000ms automatically. setTimeout() is the one you have to setup every time again.
As others have pointed out, you are creating new interval every time.
Move it to outside your function.
function tick()
{
var d = new Date();
var time = padNumber(d.getHours(),2)+':'+padNumber(d.getMinutes(),2);
$('#WeatherBoLfTime').html(' '+time);
}
$(document).ready(function(){
t = setInterval(tick,60000);
})
Edit: I'm slow and other answers seem to be updated. So this one is useless now :)
Have look in below demo code, which will be updated each second...
<!DOCTYPE html>
<html>
<head>
<title>j</title>
<script type="text/javascript">
function myFunction()
{
setInterval(function(){
var d = new Date();
document.getElementById("dates").innerHTML = new Date(d.getTime());}, 1000);
}
</script>
</head>
<body>
<input type="button" name="e" onclick="myFunction()">
<p id= "dates">ok</p>
</body>
</html>

Categories

Resources