How to create a javascript timer? - javascript

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.

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'

Why does setInterval not increment my clock properly in JavaScript?

I want to display the actual time in New York. I have a html div:
<div id="time"></div>
and also - I have a php script that returns the actual time:
<?php
date_default_timezone_set('UTC');
echo time();
?>
and it does it as a timestamp.
Now, I've created a js script:
var serverTime;
moment.tz.add('America/New_York|EST EDT|50 40|0101|1Lz50 1zb0 Op0');
function fetchTimeFromServer() {
$.ajax({
type: 'GET',
url: 'generalTime.php',
complete: function(resp){
serverTime = resp.responseText;
function updateTimeBasedOnServer(timestamp) { // Take in input the timestamp
var calculatedTime = moment(timestamp).tz("America/New_York");
var dateString = calculatedTime.format('h:mm:ss A');
$('#time').html(dateString + ", ");
};
var timestamp = serverTime*1000;
updateTimeBasedOnServer(timestamp);
setInterval(function () {
timestamp += 1000; // Increment the timestamp at every call.
updateTimeBasedOnServer(timestamp);
}, 1000);
}
})
};
fetchTimeFromServer();
setInterval(function(){
fetchTimeFromServer();
}, 5000);
and the idea behind it is that I want to fetch the data from server, display it on my webpage, then increment it every second for five seconds and then fetch the time from the server again (to keep consistence with time on the server). And later on - continue with doing so, fetching the time, incrementing it for 5 seconds, fetching it again, etc.
It works... almost. After the webpage stays open for some time I can see the actual time, but it 'blinks', and I can see that it shows different times - it's hard to explain, but it looks like there is some time already in that div and new time tries to overlay it for each second. Seems like the previous time (content of this div) is not removed... I don't know how to create a jsfiddle with a call to remote server to fetch time from php, so I only have this information pasted above :(
What might be the problem here?
Since javascript is single threaded, setInterval may not acutally run your function after the delay. It adds the function to the stack to be run as soon as the processor is ready for it. If the processor has other events in the stack, it will take longer than the interval period to run. Multiple intervals or timeouts are all adding calls to the same stack for processing. To address this, you could use HTML5 web workers or try using setTimeout recursively.
Here is a good read on web workers: https://msdn.microsoft.com/en-us/hh549259.aspx

How to reload page when jquery.counter trigger finish.countdown event for multiple instance?

I am using multiple instance for jQuery countdown and implement page reload when counter get finished
E.g.
$('.countdown').each(function() {
var $this = $(this),
finalDate = $(this).data('countdown');
$this.countdown((finalDate), function(event) {
var days = event.strftime('%D');
$(this).find('.days').children('span').html(days);
$(this).find('.hours').children('span').html(event.strftime('%H'));
$(this).find('.minutes').children('span').html(event.strftime('%M'));
$(this).find('.seconds').children('span').html(event.strftime('%S'));
});
$(this).on('finish.countdown', function(event){
/*if(!window.location.hash && !(window.location.hash.indexOf('_loaded') > -1)) {
window.location = window.location + '#_loaded'; window.location.reload();
}*/
//If I put window location reload here it will goes into infinite loop. Also above commented code will reload page twice initially which is also not valid solution.
});
});
Issue: If countdown is already finished (E.g. 00:00:00:00 ) then page reload occur twice when script loaded at first time,
I have used localStorage concept but unable to find exact solution. Please help
I had almost this issue with page constantly reloading instantly.
Try and check if your local time and server time are the same. In my case, the difference was two hours, which was the issue that put the page into constant loop.
Countdown plugin has some notes on timezone awareness: http://hilios.github.io/jQuery.countdown/examples/timezone-aware.html

Refresh just home page

I am currently designing a system which includes a homepage that show the person who logs in only the work they have to do. I have been asked to set up this homepage to refresh every 3 minutes which I have done using this code:
function startTimer() {
var now = new Date();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var secTime = minutes*60*seconds;
if(secTime % (3*60) == 0){
var refreshTime = 3*60*1000;
} else {
var refreshTime = (secTime % (3*60)) * 1000;
}
setTimeout('refresh()', refreshTime);}
function refresh() {
window.location.href = 'myURL';
}
startTimer();
The problem I currently have is that when I navigate away from this page, but still in the system, it keeps returning me to homepage and I lose what I am working on.
Is there a way that I can keep refreshing homepage for those who haven't moved away from it and stop it when someone does?
I am very new to Javascript so please be patient if I ask a lot of question.
Thank you in advance for any help given.
I assume you are using a shared javascript file on all pages of the site which is why the timer will keep running on every page. You could make sure that the timer only runs on the homepage by checking the page url and wrap your startTimer function inside this check:
if (document.location.href == "http://www.yourhomepage.com"){
startTimer();
}
Replace http://www.yourhomepage.com with whatever url your homepage is on. This will only work if your pages are separate html files. If you are using a hashbang method whereby the document doesn't change, this will not work.
You can use Ajax to refresh the work log part of the page instead of refreshing the whole page.
When you refresh your page, your code redirect you to your home page because of window.location.href = 'myURL';. The location change, and it redirect you everytime to 'myURL'.
You would like to refresh only a part of your page. You have to send a XMLHttpRequest or Ajax request ( you load a page into your current page without reloading your current page ). https://developer.mozilla.org/fr/docs/XMLHttpRequest
When you get the page loaded, you insert the text loaded into the page.
Then, call the function which send request, every "refreshTime" like that
function sendAjax(){
// ... ajax request
// refreshTime = 3 * 60 * 1000;
setTimeout( sendAjax, refreshTime );
}
sendAjax();
Don't use quote arround the function name in setTimout. setTimemout need a function to call (not his name but his value) and time parameters.

How to have a timer which cannot be modified in javascript?

Basically, I am designing a quiz application with limited time. Use selects answer to a question and the next question loads using an Ajax request. All questions must be answered within a time frame of, say 2 minutes.
A clock ticks away to show how much time is left and as soon as it hits 0, results are shown. Now since the timer will be implemented using window.setTimeout(), it is possible that the value of timer variable be modified using an external bookmarklet or something like that. Anyway I can prevent this? I think this is implemented on file sharing sites like megaupload. Any forgery on the timer variable results in request for file being rejected.
Have .setTimeout() call an AJAX method on your server to synch time. Don't rely on the client time. You could also store the start time on the server for a quiz, and then check the end time when the quiz is posted.
You need to add a validation in your server side. When the client want to load the next question using an Ajax request, check whether deadline arrived.
The timer in client side js just a presention layer.
If the function runs as a immediately called function expression, then there are no global variables and nothing for a local script to subvert. Of course there's nothing to stop a user from reading your code and formulating a spoof, but anything to do with javascript is open to such attacks.
As others have said, use the server to validate requests based on the clock, do not rely on it to guarantee anything. Here's a simple count down that works from a start time so attempts to dealy execution won't work. There are no global variables to reset or modify either.
e.g.
(function (){
// Place to write count down
var el = document.getElementById('secondsLeft');
var starttime,
timeout,
limit = 20; // Timelimit in seconds
// Function to run about every second
function nextTick() {
var d = new Date();
// Set start time the first time
if (!starttime) starttime = d.getTime();
var diff = d.getTime() - starttime;
// Only run for period
if (diff < (limit * 1000)) {
el.innerHTML = limit - (diff/1000 | 0);
} else {
// Time's up
el.innerHTML = 0;
clearTimeout(timeout);
}
}
// Kick it off
timeout = window.setInterval(nextTick, 1000);
}());

Categories

Resources