Session Timeout doesn't work by using javascript - javascript

I have below script. When the time is 60 sec or less the popup is appear(which asks user for whether to log out or continue) and when I click on continue from that button of popup it reloads the page. The issue is sometimes it goes logged out. Not sure whats wrong with below code. Any help is appriciated.
var startTime = new Date();
var endTime = new Date(startTime.getTime() + (#FormsAuthentication.Timeout.TotalMilliseconds));
var i = 0;
function updateTimeoutDuration() {
var diff = Math.floor((new Date() - endTime) / 1000) * -1;
if (diff > 0) {
minutes = Math.floor(diff / 60);
seconds = Math.floor(diff % 60);
$('#timeout-countdown #remaining-time').html(((minutes < 10) ? '0' : '') + minutes + ':' + ((seconds < 10) ? '0' : '') + seconds);
console.log("Timeout - countdown",((minutes < 10) ? '0' : '') + minutes + ':' + ((seconds < 10) ? '0' : '') + seconds);
$('#dialog-timeout-confirm #timeout-countdown-popup #remaining-time-popup').html(((minutes < 10) ? '0' : '') + minutes + ':' + ((seconds < 10) ? '0' : '') + seconds);
// popup message will display when 60 sedconds remaining
if (diff < 60) {
// Autometically logged out when 0 second when timer will reach to 0 second
if (diff < 1) {
$("#logoutfrm").submit();
}
$('#timeout-countdown #remaining-time').addClass('warning');
$('#dialog-timeout-confirm #timeout-countdown-popup #remaining-time-popup').addClass('warning');
//Popup message will open
if (i == 0) {
i = 1;
popupMessage();
}
i = 1;
}
}
else {
window.location.href = '#FormsAuthentication.LoginUrl' + '?redirectUrl=' + encodeURIComponent(window.location.pathname);
}
}
$(function () {
setInterval(updateTimeoutDuration, 1000);
});
function popupMessage()
{
$("#dialog-timeout-confirm").dialog({
resizable: false,
height: 240,
modal: true,
buttons: [
{
text: "Log out",
"class": 'popup_logoutbtn',
click: function() {
var logoutfrm = document.getElementById('logoutForm');
if(logoutfrm != undefined && logoutfrm != null && logoutfrm != ''){
//logoutfrm.submit();
$("#logoutfrm").submit();
}
else{
window.location.href = '#FormsAuthentication.LoginUrl' + '?redirectUrl=' + encodeURIComponent(window.location.pathname);
}
}
},
{
text: "Stay Logged In",
"class": 'popup_staylogoutbtn',
click: function() {
location.reload();
}
}
]
});
}

Related

How to replace "0:00" with "Collect" in timer button

In the last days I had asked a question how to make a button that is disabled for 1 minute and when it is clickable again +25 points are added to a div. The problem is: When the timer is over it says "0:00". Is there a way to replace the "0:00" with "Collect"? I found similar questions on stackoverflow but they didn't help me.
Here is my code:
$('#btn').prop('disabled',true);
startCountDown();
function getCounter(){
return parseInt($('#counter').html());
}
function setCounter(count) {
$('#counter').html(count);
}
$("#btn").click(function() {
setCounter(getCounter()+25);
$('#btn').prop('disabled',true);
startCountDown();
});
function startCountDown() {
var minutes = 0,
seconds = 59;
$("#countdown").html(minutes + ":" + seconds);
var count = setInterval(function() {
if (parseInt(minutes) < 0 || parseInt(seconds) <=0 ) {
$("#countdown").html(minutes + ":" + seconds);
clearInterval(count);
$('#btn').prop('disabled',false);
} else {
$("#countdown").html(minutes + ":" + seconds);
seconds--;
if (seconds < 10) seconds = "0" + seconds;
}
}, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="counter">0</div>
<button id="btn">
<span id="countdown">0:00</span>
</button>
UPDATE:
I have updated my code as you can see in the second snippet. Unfortunately, I now have the problem that the number 0:01 has been replaced with "Collect". (So: 0:03, 0:02, Collect(disabled), Collect(enabled)). Here is the code:
$('#btn').prop('disabled',true);
startCountDown();
function getCounter(){
return parseInt($('#counter').html());
}
function setCounter(count) {
$('#counter').html(count);
}
$("#btn").click(function() {
setCounter(getCounter()+25);
$('#btn').prop('disabled',true);
startCountDown();
});
function startCountDown() {
var minutes = 0,
seconds = 60;
$("#countdown").html(minutes + ":" + seconds);
var count = setInterval(function() {
if (parseInt(minutes) < 0 || parseInt(seconds) <=0 ) {
$("#countdown").html(minutes + ":" + seconds);
clearInterval(count);
$('#btn').prop('disabled',false);
} else {
$("#countdown").html(minutes + ":" + seconds);
seconds--;
if (seconds < 10) seconds = "0" + seconds;}
if (seconds == 0) {// replacing 0:00 with "Collect" is right here
$('#countdown').html("Collect");
}
}, 1000);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="counter">0</div>
<button id="btn">
<span id="countdown">Collect</span>
</button>
Hello GuciiBananaKing99,
I have found the solution to your problem. You need to add an if statement when seconds is 0. Then change $('#btn').html to "Collect".
Here is the full code:
function startCountDown() {
var minutes = 0,
seconds = 59;
$("#countdown").html(minutes + ":" + seconds);
var count = setInterval(function() {
if (parseInt(minutes) < 0 || parseInt(seconds) <=0 ) {
$("#countdown").html(minutes + ":" + seconds);
clearInterval(count);
$('#btn').prop('enabled',false);
} else {
$("#countdown").html(minutes + ":" + seconds);
seconds--;
if (seconds < 10) {seconds = "0" + seconds;}
if (seconds == 0) { // Check if seconds is 0
$('#btn').html("Collect"); // Change Btn's HTML to Collect
});
}
}, 1000);
}

JavaScript - can't make the timer function to be called when the page is loaded

I'm trying to make my simple timer function to be called when the page is loaded. But it doesn't work. I think I made mistake somewhere in the if else loop, maby here: setTimeout(function(tag, sec), 1000);
How can I fix it?
<script>
document.addEventListener('DOMContentLoaded', function(tag, sec) {
tag = "timerPlace";
sec = 3600;
document.getElementById(tag).innerHTML = "<div id= 'inTime'>" + (sec / 60 >> 0) + 'min ' + sec % 60 + 'sec' + '<br>' + "</div>";
if ((sec / 60 >> 0) != 0 || (sec % 60) != 0) {
setTimeout(function(tag, sec), 1000);
sec -= 1;
} else {
document.getElementById(tag).innerHTML = "Time is over!";
}
}, false);
</script>
<div id="timerPlace"></div>
Try this,
javascript
// Code goes here
function saysomething() {
alert('say something');
}
document.addEventListener('DOMContentLoaded', function(tag, sec) {
tag = "timerPlace";
sec = 3600;
document.getElementById(tag).innerHTML = "<div id= 'inTime'>" + (sec / 60 >> 0) + 'min ' + sec % 60 + 'sec' + '<br>' + "</div>";
if ((sec / 60 >> 0) != 0 || (sec % 60) != 0) {
// setTimeout(function(tag, sec), 1000);
setTimeout(saysomething, 1000);
sec -= 1;
} else {
document.getElementById(tag).innerHTML = "Time is over!";
}
}, false);
HTML
<body>
<div id="timerPlace"></div>
</body>
or
<script>
//Timer function
window.onload = function() {
myFunction();
};
function myFunction(){
timer('timerPlace',3600);
}
function timer(tag, sec) {
document.getElementById(tag).innerHTML = "<div id= 'inTime'>" +
(sec / 60 >> 0) + 'min ' + sec % 60 + 'sec' + '<br>' + "</div>";
if ((sec / 60 >> 0) != 0 || (sec % 60) != 0) {
setTimeout(function() {
timer(tag, sec);
}, 1000);
sec -= 1;
} else {
document.getElementById(tag).innerHTML = "Time is over!";
}
}
</script>
<div id="timerPlace"></div>
<br>
<br>
<br>
<br>
<!-- Write number of seconds here: onclick="timer('str',...here!...) -->
<button class="button" onclick="timer('timerPlace',3600); style.display = 'none'"> <span>Start Test</span>
</button>
<!-- Place this div where you whant timer to be. -->
https://jsfiddle.net/Lk963xa0/
Made an example with Jquery, not sure if this is what you are looking for
JS
$(document).ready(function(){
tag = "timerPlace";
sec = 15;
var timer = function(){
setTimeout(function(){
sec--;
document.getElementById(tag).innerHTML = "<div id= 'inTime'>" + sec + "</div>"
if(sec === 0 ){console.log("time is out"); return}
timer();
}, 1000);
};
timer();
});
HTML
<div id="timerPlace"></div>
I corrected your code. I still don't really know what you are trying to achieve.
setTimeout callback is empty for you to write what it needs to do.
This is the correct way to wait for the DOM to be ready before executing a query looking for an element in it.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
var tag = "timerPlace";
var sec = 3600;
document.getElementById(tag).innerHTML = "<div id= 'inTime'>" + (sec / 60 >> 0) + 'min ' + sec % 60 + 'sec' + '<br>' + "</div>";
if ((sec / 60 >> 0) != 0 || (sec % 60) != 0) {
setTimeout(function() {
//Do something after 1000
}, 1000);
sec -= 1;
} else {
document.getElementById(tag).innerHTML = "Time is over!";
}
});
jsFiddle
Edit:
To execute after page load, use this:
window.addEventListener('load', function () {
//Code to execute after page load
});

How to refresh timer when click on link in javascript

I have countdown time for 15 seconds. It refreshes when 1 second on it. I also need refresh timer when user clicks at link on my website. I use cookie to provide no refreshing of timer when user refreshes page. Now when I click at link my timer refreshes but my old timer continues to countdown. As a result I have two timers and every second I see values from different timers. For example: I have countdown timer for 15 second. I click at link when value on timer was 7 seconds, and I see something like this: 15, 6, 14, 5, 13, 4, 12, 3 etc. But I need normal sequnce such 15, 14, 13 etc. What should I do for it? Below is my code:
// calls when I click at link
function rate(auct_id){
$.ajax({
type: 'POST',
url: '/auth/rate',
data: {'id': auct_id },
success: function(data) {
data = jQuery.parseJSON(data);
if (data.message) {
alert(data.message);
if (data.message != 'rates_count') {
windows.location = '/#openModal';
}
} else {
var new_price = data.price;
var new_login = data.login;
new_price += '<span> руб.</span>';
$('#price_' + auct_id).html(new_price);
$('#login_' + auct_id).html(new_login);
setTimer(auct_id, true);
}
}
});
}
function setTimer(id, update) {
var countdown4;
if(getCookie('countdown_' + id) && !update) countdown4 = getCookie('countdown_' + id);
else countdown4 = 15;
if (update) delete_cookie('countdown_' + id);
do_cd4(id, countdown4, update);
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
var delete_cookie = function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
function convert_to_time(secs) {
secs = parseInt(secs);
hh = secs / 3600;
hh = parseInt(hh);
mmt = secs - (hh * 3600);
mm = mmt / 60;
mm = parseInt(mm);
ss = mmt - (mm * 60);
if (hh > 23) {
dd = hh / 24;
dd = parseInt(dd);
hh = hh - (dd * 24);
} else {
dd = 0;
}
if (ss < 10) {
ss = "0" + ss;
}
if (mm < 10) {
mm = "0" + mm;
}
if (hh < 10) {
hh = "0" + hh;
}
if (dd == 0) {
return (hh + ":" + mm + ":" + ss);
}
else {
if (dd > 1) {
return (dd + " day " + hh + ":" + mm + ":" + ss);
} else {
return (dd + " day " + hh + ":" + mm + ":" + ss);
}
}
}
// Our function that will do the actual countdown
do_cd4 = function(id, countdown4, update) {
//console.log(countdown4);
if (countdown4 < 1) {
countdown4 = 15;
do_cd4(id, countdown4);
} else {
$('#timer_' + id).html(convert_to_time(countdown4));
setTimeout(function() {
do_cd4(id, countdown4, update);
}, 1000);
}
setCookie('countdown_' + id, countdown4, 3);
countdown4 = countdown4 - 1;
}
The question has already been asked : Resetting a setTimeout
You need to keep a reference on your setTimeout, so you can clear it or restart it.

Javascript box that takes answer and updates

I've gone over this for hours trying different things and can't get it to work, I've made a dice that rolls every 10 seconds, the timer and the dice roll shows on screen and constantly updates the roll. I want to make a box that shows the previous 5 rolls of the dice and constantly updates. Not sure if I have to make separate function or add it to my existing function. Here is what I have so far.
<script type = "text/javascript">
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
}
function tick( ) {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else {
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1;
die1.innerHTML = d1;
status.innerHTML = "Dice Roll "+diceTotal+".";
clearInterval(ticker);
startTimer(0000010); // start again
}
var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
}
startTimer(0000010);
</script>
One option would be to have 5 predefined divs and have them cleared/filled dynamically.
Another option is to keep the roll history in an array and fill the 'history element' from that array.
For example:
rolls.push(d1); //add roll to history
if(rolls.length > maxrollhistory)
rolls.shift();
die1.innerHTML = 'Previous rolls: ' + rolls.reduce(function(prev,cur){return '<span class="rollhistory">' + cur + ' </span>' + prev; }, '');
where rolls is the array containing the history. (rollhistory is a class I made up to format the results).
In the underlying example I took the liberty of restructuring the program to display the above (click here for fiddle ) :
var die1 = document.getElementById("die1"),
status = document.getElementById("status");
function startTimer(secs) {
var timeInSecs = parseInt(secs),
rolls = [],
rem = 0,
maxrollhistory = 5,
roll = function(){
var d1 = Math.floor(Math.random() * 6) + 1;
rolls.push(d1); //add roll to history
if(rolls.length > maxrollhistory)
rolls.shift();
die1.innerHTML = 'Previous rolls: ' + rolls.reduce(function(prev,cur){return '<span class="rollhistory">' + cur + ' </span>' + prev; }, '');
status.innerHTML = "Dice Roll "+ d1 +".";
},
tick = function(){
if (--rem <= 0) {
rem = timeInSecs;
roll();
}
var secs = rem;
var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
setTimeout(tick,1000);
}
tick();
}
startTimer(10);
All you need is to append. Check the snippet added status.innerHTML += "Dice Roll "+diceTotal+".<br>";
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
}
function tick( ) {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
}
else {
var die1 = document.getElementById("die1");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1;
die1.innerHTML = d1;
status.innerHTML = "Dice Roll "+diceTotal+".<br>" +status.innerHTML;
clearInterval(ticker);
startTimer(0000010); // start again
}
var mins = Math.floor(secs/60);
secs %= 60;
var pretty = ( (mins < 10) ? "0" : "" ) + mins + ":" + ( (secs < 10) ? "0" : "" ) + secs;
document.getElementById("countdown").innerHTML = pretty;
}
startTimer(0000010);
<div id="countdown"></div> <div id="die1" class="dice">0</div> <h2 id="status" style="clear:centre;"></h2>

JS Code Works in jsbin and Not in jsfiddle or Chrome/Safari?

I am trying to figure out why this code is working only in jsbin and not in jsfiddle or in any web browser as an html/js file. I have tried debugging but cannot find a conclusion.
I made the mistake of coding directly in jsbin instead of a document. Any input would be appreciated.
http://jsbin.com/tuduxedohe/7/edit
http://jsfiddle.net/2rs1x5pz/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Timer</title>
<script type="text/javascript" src="part2.js"></script>
</head>
<body>
<h1><div id="time">00:00:00</div></h1>
<div id="result"></div>
<button id="start" onclick ="startClock();" >Start</button>
<button id="stop" onclick="stopTimer();">Stop</button>
<button id="clear" onclick="resetTimer();">Reset</button>
</body>
</html>
var currentTime = document.getElementById('time');
var hundreths = 0;
var seconds = 0;
var minutes = 0;
var t;
function startClock() {
function add() {
hundreths++;
if (hundreths > 99) {
hundreths = 0;
seconds++;
if (seconds > 59) {
seconds = 0;
minutes++;
}
if(minutes >= 10) {
seconds= 0;
minutes= 0;
stopTimer();
}
}
if (hundreths > 9 && seconds < 9) {
currentTime.innerHTML = "0" + minutes + ":" + "0" + seconds + ":" + hundreths;
}
else if ((seconds > 9 ) && (hundreths < 9)) {
currentTime.innerHTML = "0" + minutes + ":" + seconds + ":" + "0" + hundreths;
}
else if((seconds > 9) && (hundreths > 9)) {
currentTime.innerHTML = "0" + minutes + ":" + seconds + ":" + hundreths;
}
else if ((minutes > 9) && (seconds < 9) && (hundreths < 9)) {
currentTime.innerHTML = minutes + ":" + "0" + seconds + ":" + "0" + hundreths;
}
else if ((minutes > 9) && (seconds > 9) && (hundreths < 9)) {
currentTime.innerHTML = minutes + ":" + seconds + ":" + "0" + hundreths;
}
else if ((minutes > 9) && (seconds > 9) && (hundreths < 9)) {
currentTime.innerHTML = minutes + ":" + seconds + ":" + hundreths;
}
else {
currentTime.innerHTML = "0" + minutes + ":" + "0" + seconds + ":" + "0" + hundreths;
}
timer();
}
function timer() {
t = setTimeout(add, 1);
}
timer();
} // end function start clock
function stopTimer() {
document.getElementById("result").innerHTML = "<p>" + ("Your time is: " + minutes + " minutes, " + seconds + " seconds, " + "and " + hundreths + " hundreths") + "</p>";
clearTimeout(t);
}
function resetTimer() {
hundreths = 0;
seconds = 0;
minutes = 0;
currentTime.innerHTML = "00:00:00";
}
That is because by default the script is added in a onload handler in jsfiddle, so your methods is available only inside the scope of that closure. So it will be
window.onload=function(){
//your script is here
}
You are trying to access them in global scope when you are trying to call them from on<event>="" attributes which will give an error like Uncaught ReferenceError: startClock is not defined in your console.
Change the second dropdown in the left panel under Frameworks & Extensions to body/head in the left panel of fiddle to add the script without a wrapper function
Demo: Fiddle

Categories