I'm trying to write a session timeout counter, so that after 15 minutes of inactivity the customer basket is deleted, the code I have so far half works but I cannot work out how to create the counter to keep track of the time. I have set the time to a low number to test
$(document).ready(function() {
var sessionTimeoutWarning =1;
var sessionTimeout = 3;
var sTimeout = parseInt(sessionTimeoutWarning) * 60 * 1000;
var timeOnPageLoad = new Date();
setTimeout(sessionWarning(), sTimeout);
function sessionWarning() {
var minutesForExpiry = (parseInt(sessionTimeout) - parseInt(sessionTimeoutWarning));
var message = "Your session will expire in another " + minutesForExpiry + " mins! Please continue browsing before your basket is deleted.";
alert(message);
var currentTime = new Date();
var timeForExpiry = timeOnPageLoad.setMinutes(timeOnPageLoad.getMinutes() + parseInt(sessionTimeout));
if (Date.parse(currentTime) > timeForExpiry) {
alert("Session expired. Items in the basket will be deleted.");
window.location = "/";
}
}
});
Any help would be appreciated
Related
Problem is my timer was working as well. But when i save timers value to localStorage. I just want to when user refresh timer wont stop and resume when stopped at.
javascript
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m<0){ document.myform.submit(); }
document.getElementById('timer').innerHTML =
m + ":" + s;
setTimeout(startTimer, 1000);
var startTime = document.getElementById("timer").value;
localStorage.setItem("startTime", startTime);
//alert(startTime);
}
function Dahin(){
var startTime = localStorage.getItem("startTime");
document.getElementById('timer').value = startTime;
}
in my view
<h3 onload="Dahin();" class="page-title">Шалгалтын 50 асуулт</h3><h4><div>Үлдсэн хугацаа = <span id="timer">{{ $time }}</span></div></h4>
Update fixed timer
now how to save timer value to sessionstorage and retrieve when refresh page
Let change your code:
var check = localStorage.getItem("startTime");
var startTime = check ? check : document.getElementById("timer").innerHTML;
document.getElementById('timer').value = startTime;
function Dahin(){
localStorage.setItem("startTime", startTime);
}
the problem why you get null is because you use .value. You put your time into span tag. .value is only work for input field
I am having an issue with reseting a JS timer in a one state app that uses ajax to load new pages, so the page rarely experiences a full reload. The timer is used to countdown the date on inquiry pages (similar concept to ebay) and there are multiple inquiry pages - all with different timers and expiry dates.
The timer works perfectly on a full page reload, but after that, it gets increasingly faster and starts storing all the different timers simultaneously (e.g. if I visited three inquiry pages and initialized three timers, now its gonna count 3 seconds per second instead of 1.)
Here is my timer function
var timer = {
isActive : null,
firstLoad : null,
currentTime: null,
distance : null,
duration : null,
init: function() {
var scope = timer;
if (scope.isActive) {
scope.counter();
}
else {
$("#countdown").html("-");
}
},
counter: function() {
var scope = timer;
scope.countdown = setInterval(function() {
if (scope.firstLoad) {
scope.distance = scope.activeTo - scope.currentTime;
scope.duration = moment.duration(scope.distance);
scope.firstLoad = false;
}
else {
scope.duration.subtract(1, "second");
}
// Time calculations for days, hours, minutes and seconds
var days = scope.duration.days();
var hours = scope.duration.hours();
if (hours < 10) {
hours = "0" + hours;
}
var minutes = scope.duration.minutes();
if (minutes < 10) {
minutes = "0" + minutes;
}
var seconds = scope.duration.seconds();
if (seconds < 10) {
seconds = "0" + seconds;
}
// Display the result in the element with id="countdown"
jQuery("#countdown").html(days + " <%= pdo.translate("countdown.days.label")%> " + hours + ":" + minutes + ":" + seconds);
// If the count down is finished, write some text
if (scope.distance < 0) {
$("#addNewBid, #cancelInquiry, #editInquiry").hide();
$("#countdown").html("<%= pdo.translate("countdown.timeend.label")%>");
}
}, 1000);
},
reset: function() {
var scope = timer;
clearInterval(scope.countdown);
scope.isActive = null;
scope.firstLoad = null;
scope.currentTime = null;
scope.distance = null;
scope.duration = null;
}
};
And this is how I reset and initialize it on new page load.
$(document).ready(function ($) {
timer.reset();
timer.currentTime = new moment("<%=pdo.getTime()%>");
timer.activeTo = new moment("<%= pdo.getInquiry().getActiveTo() %>");
timer.isActive = <%=pdo.getInquiry().isActive()%>;
timer.firstLoad = true;
timer.init();
});
I'm sorry if this question is a bit tricky but I have no other way of asking it and I am an absolute noob in javascript world.
I have this javascript counter that someone helped me to gather on stackoverflow and it works fine BUT
the countdown timer will start from the beginning on a different browsers.
i.e. when I look at it on Firefox, it will carry on counting down and it will keep working as it should. lets say the timer is set to countdown a day. on Firefox it will show 23:24 hours/minutes left but if I open a new browser (any browser), it will show the timer 23:59 hours/minutes left and it will start counting down from there... even though the countdown timer was already running on the same page!!
here is the code:
<script type="text/javascript">
var EXPIRY = parseInt(new Date().getTime()/1000) + 24*60*60;
var counter = null;
var counter_interval = null;
function setCookie(name,value,days) {
console.log("setting "+name+" "+value);
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else {
expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
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,c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length,c.length);
}
}
return null;
}
function deleteCookie(name) {
setCookie(name,"",-1);
}
function resetCounter() {
EXPIRY = parseInt(new Date().getTime()/1000) + 24*60*60;
}
function stopCounter() {
window.clearInterval(counter_interval);
deleteCookie('Expiry');
}
function updateCounter() {
var msg = '';
curTime = parseInt(new Date().getTime()/1000);
if (curTime < EXPIRY) {
msg = convertSecondsToDays(EXPIRY - curTime);
}
else {
EXPIRY = parseInt(new Date().getTime()/1000) + 24*60*60;
}
var el = document.getElementById('counter');
if (el) {
el.innerHTML = msg
}
}
function convertSecondsToDays(sec) {
var days, hours,rem,mins,secs;
days = parseInt(sec/(24*3600));
rem = sec - days*3600
hours = parseInt(rem/3600);
rem = rem - hours*3600;
mins = parseInt(rem/60);
secs = rem - mins*60;
return days +":" + hours +":"+mins + ":"+ secs + "";
}
function startCounter() {
stopCounter();
setCookie('Expiry', EXPIRY, 1);
counter_interval = window.setInterval(updateCounter, 1000);
}
function init() {
EXPIRY = getCookie('Expiry');
if (!EXPIRY) {
console.log("unable to find cookie");
resetCounter();
}
startCounter();
}
init();
</script>
you can view it on the fiddle here: http://jsfiddle.net/h2DEr/1/
how can i make it in a way that it will show the same time left on all the browsers as it will be displayed on the same page?
Thanks
Edit:
I found this code which works with mysql. it works fine but instead of counting down it will show how many days/hours/minutes the product/item was posted on the site. and this doesn't need any javascript as is...
This is sort of what I am looking for but instead of counting up it needs to countdown:
<?php
//list fields and convert to seconds
$countdown['days']=(5) * 24 * 60 * 60;
$countdown['hours']=(3) * 60 * 60;
// etc, etc
$countsum=time() + $countdown['days'] + $countdown['hours']; //and so on
// the above would be the timestamp to enter into the table
##########
// 'dumbed down' query
include "config/connect_to_mysql.php";
$result=mysql_query("SELECT * FROM tomProduct WHERE id='id';");
while ($row=mysql_fetch_assoc($result))
$time=$row['date_added'] - time(); //this field would be a PHP timestamp (time())
$count=getdate($time);
$x=getdate(); //todays information
$count['mday'] -= $x['mday'];
$count['hour'] -= $x['mday'];
$count['minutes'] -= $x['minutes'];
echo "$count[mday] Days $count[hour] Hours $count[minutes] Minutes"; //etc
// untested, but should work
?>
JavaScript is always running on the client. One instance of the timer has no knowledge of any other instance running elsewhere.
To synchronize time between different browsers, you would need server-side scripts.
Using expiration-time-stamps in a server-side script in conjunction with JavaScript timers should give you the synchronization you are looking for.
Cookies are not transferred from browser to browser. They are stored in the web browser.
I want to make a countdown timer, that can be used on several places in the same page - so I think it should be a function in some way.
I really want it to be made with jQuery, but I cant quite make it happen with my code. I have e.g. 10 products in a page, that I need to make a countdown timer - when the timer is at 0 I need it to hide the product.
My code is:
$(document).ready(function(){
$(".product").each(function(){
$(function(){
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var count = Seconds_Between_dates;
var elm = $(this).attr('id');
alert(elm);
countdown = setInterval(function(){
$(elm + " .time_left").html(count + " seconds remaining!");
if (count == 0) {
$(this).css('display','none');
}
count--;
}, 1000);
});
});
});
EDIT 1:
$(document).ready(function(){
$(".product").each(function(){
var elm = $(this).attr('id');
$(function(){
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
var count = Seconds_Between_dates;
alert(elm);
countdown = setInterval(function(){
$(elm + " .time_left").html(count + " seconds remaining!");
if (count == 0) {
$(this).css('display','none');
}
count--;
}, 1000);
});
});
});
Do you have any solutions to this?
I'd probably use a single interval function that checks all the products. Something like this:
$(function() {
/* set when a product should expire.
hardcoded to 5 seconds from now for demonstration
but this could be different for each product. */
$('.product').each(function() {
$(this).data('expires', (new Date()).getTime() + 5000);
});
var countdown_id = setInterval(function() {
var now = (new Date()).getTime();
$('.product').each(function() {
var expires = $(this).data('expires');
if (expires) {
var seconds_remaining = Math.round((expires-now)/1000);
if (seconds_remaining > 0) {
$('.time-left', this).text(seconds_remaining);
}
else {
$(this).hide();
}
}
});
}, 1000);
});
You could also cancel the interval function when there is nothing left to expire.
Your problem seems to be that this doesn't refer to the current DOM element (from the each), but to window - from setTimeout.
Apart from that, you have an unnecessary domReady wrapper, forgot the # on your id selector, should use cached references and never rely on the timing of setInterval, which can be quite drifting. Use this:
$(document).ready(function(){
$(".product").each(function(){
var end = new Date(/* from something */),
toUpdate = $(".time_left", this);
prod = $(this);
countDown();
function countdown() {
var cur = new Date(),
left = end - cur;
if (left <= 0) {
prod.remove(); // or .hide() or whatever
return;
}
var sec = Math.ceil(left / 1000);
toUpdate.text(sec + " seconds remaining!"); // don't use .html()
setTimeout(countdown, left % 1000);
}
});
});
I am working on the following code for a chrome extension. Basically I want it to check the page that initially loads and if it matches my website st.mywebsite.com it will execute the code. Right now it doesn't check and will execute any pages that loads. I am trying to get it to load http://st.mywebsite.com/?q= plus the terms in the array. So every X number of seconds/minutes it will load a new term in the array and add it to the url http://st.mywebsite.com/?q=can anyone help?
if((window.location.hostname != "st.mywebsite.com")){
window.onload = function() {
terms = new Array("5d65sd", "95sd4s", "h2j4g8h", "c87e2dd", "e6e5f2g4", "3m5g5gv");
min = 1;//minimum
max = 60;//maximum
randomnumber = Math.floor(Math.random() * (max - min + 1)) + min;
var seconds = randomnumber;
var timer;
function countdown() {
var container = document.getElementById('right');
seconds--;
if(seconds > 0) {
container.innerHTML = '<p>Please wait <b>'+seconds+'</b> seconds.</p>';
} else {
window.location = 'http://st.mywebsite.com/?q='+terms;
}
}
timer = setInterval(countdown, 1000);
}
}
At the line you have window.location, change it to window.location.href