Reputation: 131
I have a timer in my checkout page, we have a 2 step checkout after step1 the web page reloads to step2 and hence the timer restarts. I need the timer to continue
Here is my code
This is javascript
<input type="hidden" id="dealCost" name="dealCost" value="${model.dealCost}"/>
<script type="text/javascript">
var dealCst = document.getElementById('dealCost').value;
if(dealCst < 53){
zi_inceput1 = new Date();
ceas_start1 = zi_inceput1.getTime();
function initStopwatch1() {
var timp_pe_pag1 = new Date();
return ((timp_pe_pag1.getTime() + (1000 * 0) - ceas_start1) / 1000);
}
var tim = 1200;
function getSecs1() {
var tSecs1 = Math.round(initStopwatch1());
if((tim-tSecs1)>=0)
{
var iSecs1 = (tim-tSecs1) % 60;
var iMins1 = Math.round((tSecs1 - 30) / 60);
var iHour1 = Math.round((iMins1 - 30) / 60);
var iMins1 = iMins1 % 60;
var min = Math.floor((tim-tSecs1) / 60);
if(min<10){
min = "0"+min;
}
var iHour1 = iHour1 % 24;
var sSecs1 = "" + ((iSecs1 > 9) ? iSecs1 : "0" + iSecs1);
var sMins1 = "" + ((iMins1 > 9) ? iMins1 : "0" + iMins1);
var sHour1 = "" + ((iHour1 > 9) ? iHour1 : "0" + iHour1);
document.getElementById('checkout_timer').innerHTML = min + ":" + sSecs1;
window.setTimeout('getSecs1()', 1000);
}
else{
window.location.href="/deals";
}
}
window.setTimeout('getSecs1()', 1000);
}
</script>
This is the html code
<c:if test='${model.dealCost < 53}'>
<div class="timer" style="float: right; width: 210px; font-size: 15px; margin-right: 20px;">
<div style="margin-top:20px;padding-bottom:5px;box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);background: white;overflow:none;">
<div class="otherheadercheckout"><div class="otherheadertextcheckout"><img src="/images/little_white_shopping_cart-19x19.png"> Timer</div></div>
<p align="center">Time left to checkout</p>
<div align="center" style="font-weight:600;">
<span id="checkout_timer"></span>
</div>
</div>
</div>
</c:if>
Upvotes: 0
Views: 621
Reputation: 707158
If you want to save the state of the timer from one page load to the next, then you have to specifically store the timer information somewhere that persists from one page to the next. Javascript variables are not saved from one page load to the next - they are reinitialized from scratch each time the page loads.
Your options are:
Server-side: use ajax to save the timer state to your server so it can be put into subsequent page loads. This is troublesome because unless you know right when the user is leaving the page and can save the remaining time to the server reliably at that moment, any sort of timer save precision would require a lot of ajax calls to the server to constantly save the time.
Client-side: Store the timer state locally via a cookie or (in newer browsers) local storage. This is easy, but can be easily manipulated by a hacker (if you care).
Upvotes: 1