So, let's say a I have two pages: "index.html" and "info.html".
In the page index.html, I have a button and a span. When the button is pressed, a countdown timer starts in that span - when the timer gets to zero, something happens. The issue is, if I start the countdown, then I go and check the info.html page, when I return to index.html, the timer resets. Of course this is caused by the script being unloaded when leaving index.html... but how to solve this? If i have something like 50 seconds remaining on the countdown, and I leave index.html, then I stay 30 seconds in the page info.html, when I come back I should have 20 seconds left.
Any ideas?
Just keep the timer information in local storage or session storage (see: Web Storage).
So for instance, on page load:
var countdownEndsAt = localStorage.getItem("countdownEndsAt");
if (countdownEndsAt) {
countdownEndsAt = +countdownEndsAt;
if (countdownEndsAt < Date.now() {
// It's already happened, decide what to do
}
}
if (!countdownEndsAt) { // Separate 'if' in case you decide to clear it in the "it's already happened" above
countdownEndsAt = Date.now() + 60000;
localStorage.setItem("countdownEndsAt", countdownEndsAt); // Gets converted to a string
}
countdownEndsAt now contains the time value at which the timer should go off.
You can save the time remaining in the local storage. When the page is refreshed the script will load the value from the local storage and start the timer with the new value:
function nonStopTimer(cb, seconds) {
var KEY = 'nonStopTimer'
var secsRemaining = localStorage[KEY];
if (!secsRemaining) {
secsRemaining = seconds;
}
setTimeout(function() {
localStorage[KEY] = null;
cb();
}, secsRemaining * 1000);
setInterval(function() {
secsRemaining -= 1;
localStorage[KEY] = secsRemaining;
}, 1000);
}
Related
I have a popup which is loaded after 30 seconds of viewing the homepage. Is it possible to have it load after 30 seconds of browsing the site and not just a particular page?
Thanks.
Update:
Current code still only loads the box after 30 seconds on each page load
var myDaemon = '';
localStorage.setItem('myTimestamp', Date.now());
if(myDaemon) clearInterval(myDaemon);
myDaemon = setInterval(function(){
var TimeDiffinSeconds = (Date.now() - localStorage.myTimestamp) / 1000;
if( TimeDiffinSeconds > 30){
requestcallback();
clearInterval(myDaemon);
localStorage.myTimestamp = Date.now();
}
},1000);
function requestcallback(){
// localStorage.clear();
var popup
if(localStorage["popup"] != null){
var timestamp = new Date().getTime(),
last_here = new Date();
last_here.setTime(localStorage["popup"]);
var current = last_here.getTime() + (7 * 24 * 60 * 60 * 1000);
if(current < timestamp){
popup = setTimeout(showPopup, 1);
}
}
else{
popup = setTimeout(showPopup, 1);
}
function showPopup(){
jQuery('.overlay').fadeIn();
clearTimeout(popup);
}
jQuery('.overlay .close').click(function(){
jQuery('.overlay').fadeOut();
var current = new Date().getTime();
localStorage["popup"] = current;
});
}
You could use Local Storage in order to save a time-stamp the moment the user visits the site , and then code a simple SetInterval to check that timestamp in specific intervals. If the difference between the current timestamp and the one saved is more than 30 seconds , you can launch your popup.
This is tricky with Javascript though. Depending on your Sites Design a different Approach is required. Also if it is for Security reasons , this is best done with AJAX and Validation through a Server. Javascript can be easily manipulated / prevented from a user and your code can be easily avoided.
A simple Example to get you going :
At your index page insert the following code :
<script>
var myDaemon = '';
localStorage.setItem('myTimestamp', Date.now());
</script>
We have declared a "var myDaemon = '';" so that we can hold our Daemons IDs in there and effectively Clearing them from any of our pages later.
Then at the Pages that you want to check for activity insert the following code :
if(myDaemon) clearInterval(myDaemon);
myDaemon = setInterval(function(){
var TimeDiffinSeconds = (Date.now() - localStorage.myTimestamp) / 1000;
if( TimeDiffinSeconds > 30){
alert('You have been browsing for more than 30 Seconds');
clearInterval(myDaemon);
localStorage.myTimestamp = Date.now();
}
},1000);
The if(myDaemon) clearInterval(myDaemon); is there to make sure we do not overlap Daemons and end up with a million of Alerts after visiting a few pages.
The clearInterval(myDaemon); after the alert is there to make sure that we stop the Daemon when we reach our goal.
The localStorage.myTimestamp = Date.now(); is there to make sure we reset our localstorage to a new Timestamp , in order to recalculate the activity of the user (if needed).
1) Define cookie functions (copy from w3school)
function setCookie(cname, cvalue, exdays) {...}
function getCookie(cname) {...}
function checkCookie() {...}
2) Create cookie if user doesn't have one
getCookie('user_first_visited') || setCookie('user_first_visited', Date.now());
3) Loop detecting if user visited over 30 seconds
if (!getCookie('user_popup_triggerred')) {
var loopDetect = setInterval(function(){
var TimePast = (Date.now() - getCookie('user_first_visited')) / 1000;
if( TimePast > 5){
alert('Browsed any page more than 5 Seconds');
clearInterval(loopDetect);
setCookie('user_popup_triggerred', 1);
}
}, 1000);
}
See jsfiddle, you can try it on two pages and you should not get popupBox on page reload after triggered once. Clean your browser cookie to try again.
I am doing an online examination page. In this page I have a countdown timer that counts down by a value from the database. It's working fine but when I refresh the page it resets. I have to stop the timer from resetting.
Here is my JavaScript timer code:
<script type="text/javascript">
function CountDown(duration, display) {
if (!isNaN(duration)) {
var timer = duration, minutes, seconds;
var interVal = setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
$(display).html("<b>" +"Time Remaining: "+ minutes + "m : " + seconds + "s" + "</b>");
if (--timer < 0) {
timer = duration;
SubmitFunction();
$('#display').empty();
clearInterval(interVal)
}
},1000);
}
}
function SubmitFunction(){
$('#result').click();
}
CountDown(<?php echo $t*30; ?>,$('#display')); //$t comes from database
function disable_f5(e) {
if ((e.which || e.keyCode) == 116) {
e.preventDefault();
}
}
$(document).ready(function(){
$(document).bind("keydown", disable_f5);
});
</script>
I just saw your question and am going to take a crack at it. One thing that I recommend is trying to commit the values to local storage. You could add an event listener, have it specify to listen for a reload, and on that reload commit the integer value to local storage in JSON format. Just an idea.
If you are using a db already, what about adding a table or an extra field to an existing table that registers the datetime that the user commenced the examination and then on each page load - you can get the commencement time from the db, do some funky calculations and then display the remaining time.
That way you are not relying on the calculation in browser keeping track (although I would probably try session storage for it as already suggested), but a constant start time that you can confidently calculate from.
try this as an approach - note only skeleton of code listed to demonstrate approach. I would personally set the datetime in the db though.
//at commencement of exam
//js var commencementTime = (//calculation to get current time);
localStorage.setItem('commencementTime ',commencementTime );
//on page reload
var commencementTime= localStorage.getItem('commencementTime ');
if(commencementTime){
//code for calculating countdown}
In my game I have set the timer to 30000ms (30 secs). When the timer ends the game ends. I want to show the user the timer to give them some idea of how long they have left. How would I do this, I have tried to do it like this:
setTimeout(function() {
$("#message").html('Thank you for playing. </br> You answered </br>' + hit + '/' + attempted + ' correctly. </br> Press "Play" to start again.').fadeIn('slow');
$(".character").fadeIn('slow');
}, 500);
});
}, 30000).show('#timer'); //here I am trying to display the time in the "#timer"
}
I think I am approaching this all wrong can someone give me a point in the right direction?
Fiddle: http://jsfiddle.net/cFKHq/8/
Have a gander at this jsFiddle. You just need to change your timeout to an interval and keep a count of the seconds.
Instead of running the timer by all 30000 at once, run the timer in 1000ms increments. Each time it hits, subtract one from the counter, refresh the page, and if the counter is 0, end the game.
I changed the jsfiddle you posted to show a counter after pushing play button. See http://jsfiddle.net/cFKHq/10/
Inside your function startplay() I added a variable ttime with an initial value of 30 and I added the line $("#timer").text(--ttime); to the setInterval argument function that is called every second.
Look into using delta times. I have found this to be a great way to handle things that need to measure changes in time.
prevTime = curTime;
curTime += new Date();
deltaTime = curTime - prevTime;
This will also allow you to have a "x seconds remaining" counter if you fire off an event every 1 second, or even every 100ms. All depends on how fast you want it to go.
You need to seperate your timer logic from your "game over" logic, as the timer should tick regardless:
var secondsLeft = 30;
var timerElement = $('#timer');
(function timer() {
timerElement.text(secondsLeft);
secondsLeft--;
if (secondsLeft !== 0) {
setTimeout(function () {
timer();
}, 1000);
}
}());
http://jsfiddle.net/cFKHq/14/
Note that in this solution the 30 * 1 second timer countdown and 30 seconds of gameplay are not related or reliant on one another, which may cause some synchronicity issues if the user is on a slow machine.
You can use a global window.duration variable were you set the seconds the game will last, then decrement from that in the "one second" interval:
See working demo
At start of script:
var hit = 0;
var attempted = 0;
var target = $("#target");
window.cont = true;
window.duration = 30; //set your desired game duration in seconds
then on the "one second interval" we decrement the timer and print the timer text:
play = setInterval(function() {
if (window.cont) {
window.cont = false;
scramble();
}
window.duration--;
$('#timer').html(window.duration + ' seconds to go');
}, 1000);
Also display a "finished" text when the game ends, the relevant part follows:
setTimeout(function() {
$("#message").html('Thank you for playing. </br> You answered </br>' + hit + '/' + attempted + ' correctly. </br> Press "Play" to start again.').fadeIn('slow');
$(".character").fadeIn('slow');
$('#timer').html('Finished');
}, 500);
Here is an example: http://jsfiddle.net/RPSMJ/4/
JavaScript
var counter = 30,
timerOutput = document.getElementById('timerOutput');
(function timer() {
timerOutput.innerHTML = counter;
counter -= 1;
if (counter >= 0) {
setTimeout(function () {
timer();
}, 1000);
}
}());
HTML
<div id='timerOutput'></div>
I have my code of timer that only alert when minutes and seconds are 0:
status = false;
hour_to_start = some_value; // THIS VALUE IS PUT FOR OTHER PERSON
min = 15; //THIS VALUE IS PUT FOR ANOTHER PERSON
seg = 60;
function timecamisa(){
if (seg > 0){
seg--;
}else{
if(seg==0){
min--;
seg=60;
}
}
if(min == 0 && seg==0){
// END - STOP ALL
min= 0;
seg = 0;
status = true;
}
var timer = min + ' minutos ' + seg + ' segundos';
document.getElementById("times-get").innerHTML = timer;
if(status != true){
setTimeout("timecamisa()",1000)//This reload this function (timecamisa())
}else{
alert("END!");
}
In my HTML i have a <span id="times-get"> where print the timer.
BUT, when i press F5 my timer return to the beginning and does not continue where you left off... So, How to do this? Anyone have a example?
My target is that my timer work with my variable 'hour_to_start' and 'min' where.. This timer displays the countdown from my variable 'hour_to_start' in 'x' 'min' (my other variable). And when the variable MIN is 0(ie, complete the mins).. Alert anything.
UPDATE!
OK, i do it with Jquery Plugin countdown Timer.. Is very useful for more than 1 timers.
Now, mi problem is.. when i change the time of my computer, this timer change too.
How to avoid changing my timer when you change the time, date and / or time of my machine?
You will need to get the time from either your server or from some remote server (e.g. via a javascript from someone else's server). If you get the time using javascript it will always depend on the clock of the user's machine.
As I don't have much knowledge of javascript and I need your help. My problem is like this:
I am using setInterval() for increasing the value of i every after 1 minutes and I am using this code:
var i = minutes;
function decrementMin() {
if(i>=0)
{
i--;
}
if(i==0)
{
alert('Minute = Congratulation your time begin now!');
}
document.getElementById('minutes').innerHTML = i + "minutes";
}
setInterval('decrementMin()',60000);
The problem is I want to show first message in <div id='minutes'></div> when page loads, but it shows the message after 1 minutes interval. If there is something that I am missing in my code please let me know.
Your problem is that you are setting the interval before the first message is displayed. Instead, you can call the function straight away and then set the interval. Also, you need to clear the interval once you've reached 0:
var i = minutes;
var intID;
function decrementMin() {
if(i>=0)
{
i--;
}
if(i==0)
{
clearInterval(intID);
alert('Minute = Congratulations my friend your time begins now!');
}
document.getElementById('minutes').innerHTML = i + "minutes";
}
decrementMin();
intID = setInterval(decrementMin, 60000);
This way you call your function straight away, and then set it to run every minute. Once you reach 0, you clear the interval so that the function doesn't count to "-1", etc.