How to reset session on keypress - javascript

I have implemented session timeout using setInterval() when the window loaded. How to reset session time on keypress event. Here is the code that I've written.
window.onload = function(){
(function(){
var counter = 60;
setInterval(function() {
counter--;
if (counter >= 0) {
//alert(counter)
span = document.getElementById("count");
span.innerHTML = counter;
}
if (counter === 0) {
$("#session-expired-modal").modal('show');
}
}, 1000);
})();
}
function sessionExpiredRedirect(){
window.location=url;
}

// Using jQuery (but could use pure JS with cross-browser event handlers):
var idleSeconds = 30;
$(function(){
var idleTimer;
function resetTimer(){
clearTimeout(idleTimer);
idleTimer = setTimeout(whenUserIdle,idleSeconds*1000);
}
$(document.body).bind('mousemove keydown click',resetTimer); //space separated events list that we want to monitor
resetTimer(); // Start the timer when the page loads
});
function whenUserIdle(){
//...your code
}

Related

Disable the click and reset it (Javascript Vanilla)

I have a problem. I created the following code! when you click on a button, a timer that lasts 3 seconds starts, the problem is that if I double click the button, the seconds go crazy, I would like to make sure that the click is reset as soon as the timer reaches 0! so that clicking again the timer always starts from 3 seconds!
document.getElementById("titolo").style.display="block"
count = 3 ;
setInterval(function(){
count--;
if(count>=0){
id = document.getElementById("titolo");
id.innerHTML = count;
}
if(count === 0){
document.getElementById("titolo").style.display="none" ;
}
},1000);
setInterval returns an ID that you can pass to clearInterval to cancel it. When the user clicks, cancel the existing ID and call setInterval again to reset it.
Capture the return value of setInterval so that later you can use it to call clearInterval.
You should disable (or hide) the button (or other element) that the user can click to start the count down.
Make sure to always declare your variables with var, let or const.
Don't use innerHTML when you only want to assign text (not HTML entities). For text (like the string representation of a counter) use textContent.
Here is how it could work:
let start = document.getElementById("start");
let id = document.getElementById("titolo");
start.addEventListener("click", function () {
start.disabled = true;
id.style.display = "block";
id.textContent = "3";
let count = 3;
let timer = setInterval(function(){
count--;
id.textContent = count;
if (count === 0) {
id.style.display = "none" ;
clearInterval(timer);
start.disabled = false;
}
}, 1000);
});
<button id="start">Start</button>
<div id="titolo"></div>
The function setInterval returns the unique id representing the interval. You can call the function clearInterval to delete that interval.
Example:
var intervalID = setInterval(function () { }, 0);
clearInterval(intervalID);
Example combined with your code:
var intervalID, count, dom = document.querySelector("#titolo");
document.querySelector("#button").addEventListener("click", onClick);
function onClick() {
clearInterval(intervalID);
dom.style.display = "block";
dom.textContent = 3;
count = 3;
intervalID = setInterval(function() {
count -= 1;
if (count >= 0) dom.textContent = count;
else {
dom.style.display = "none";
clearInterval(intervalID);
}
}, 1000);
}
<div id="titolo"></div>
<button id="button">Button</button>

timer starts automatically instead of on a button press in javascript

I'm quite new to javascript so the answer is probably quite easy but anyways
I'm trying to make a simple click speed test but i cant get the timer to start when the user presses the click me button, so i resorted to just starting it automatically. if anyone can help me to start it on the button press it will be much appreciated
HTML code:
<button id="click2" onclick="click2()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="10stimer">10s</span>
JS code:
var click = document.getElementById("click2");
var amount = 0;
var seconds = 10;
var endOfTimer = setInterval(click2, 1000);
function click2() {
seconds--;
document.getElementById("10stimer").innerHTML = seconds + "s";
if (seconds <= 0) {
var cps = Number(amount) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("click2").disabled = true;
document.getElementById("10stimer").innerHTML = "Ended";
clearInterval(seconds);
}
}
document.getElementById("click2").onclick = function() {
amount++;
document.getElementById("clicksamount").innerHTML = amount + " Clicks";
}
It looks like you're overwriting your onclick function on the button with id click2 with the lowest 4 lines.
Also, you call clearInterval() with the seconds variable instead of the actual interval, which is referenced by endOfTimer.
I'd suggest to have a separated timer management in a function which you call only on the first click of your button.
See JSFiddle
<button id="clickbutton" onclick="buttonClick()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="secondcount">10s</span>
// We will have timerStarted to see if the timer was started once,
// regardless if it's still running or has already ended. Otherwise
// we would directly restart the timer with another click after the
// previous timer has ended.
// timerRunning only indicates wether the timer is currently running or not.
var timerStarted = false;
var timerRunning = false;
var seconds = 10;
var clickAmount = 0;
var timer;
function buttonClick() {
if (!timerStarted) {
startTimer();
}
// Only count up while the timer is running.
// The button is being disabled at the end, therefore this logic is only nice-to-have.
if (timerRunning) {
clickAmount++;
document.getElementById("clicksamount").innerHTML = clickAmount + " Clicks";
}
}
function startTimer() {
timerStarted = true;
timerRunning = true;
timer = setInterval(timerTick,1000);
}
function timerTick() {
seconds--;
document.getElementById("secondcount").innerHTML = seconds + "s";
if (seconds <= 0) {
timerRunning = false;
clearInterval(timer);
var cps = Number(clickAmount) / 10;
document.getElementById("clickbutton").disabled = true;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS (" + clickAmount + "clicks in total)!";
}
}
I made some changes to your code. Effectively, when the user clicks the first time, you start the timer then. The timer variables is null until the first the user clicks.
var click = document.getElementById("click2");
var noOfClicks = 0;
var seconds = 10;
var timer = null;
function doTick(){
seconds--;
if(seconds<=0){
seconds = 10;
clearInterval(timer);
document.getElementById("10stimer").innerHTML= "Ended"
timer=null;
document.getElementById("click2").disabled = true;
}
updateDisplay()
}
function updateClicks(){
if(!timer){
timer=setInterval(doTick, 1000);
clicks= 0;
seconds = 10;
}
noOfClicks++;
updateDisplay();
}
function updateDisplay(){
var cps = Number(noOfClicks) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("10stimer").innerHTML =seconds;
}
click.addEventListener('click', updateClicks)
https://jsbin.com/bibuzadasu/1/edit?html,js,console,output
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
Use event listeners rather than onclicks
usage example:
HTML
<button id="mybutton">Click me!</button>
JS
/* ABOVE CODE ... */
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
<button id="mybutton">Click me!</button>
//state initialization
var amount = 0;
var seconds = 10;
var timedOut=false;
var timerId=-1;
//counters display
var clicksDisplay= document.getElementById("clicksamount");
var timerDisplay= document.getElementById("10stimer");
function click2(e){
//first click
if(timerId===-1){
//start timer
timed();
}
//still in time to count clicks
if(!timedOut){
amount++;
clicksDisplay.innerText=amount +" Clicks";
}
}
function timed(){
//refresh timer dispaly
timerDisplay.innerText=seconds+"s";
seconds--;
if(seconds<0){
//stop click count
timedOut=true;
}else{
//new timerId
timerId=setTimeout(timed,1000);
}
}

Popup after user has been idle

I have written some code that brings up a message for the user to either ignore the message or go to another page if they have been idle for more than a minute. Everything works, as I want it to except when the user ignores the message. Here is my code:
if ( valid ) {
var idleTime = 0;
jQuery(document).ready(function () {
var idleInterval = setInterval(timerIncrement, 60000);
});
function resetTimer() {
idleTime = 0;
}
jQuery(document)
.on('mousemove', resetTimer)
.on('keydown', resetTimer)
.on('scroll', resetTimer);
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime >= 1) {
jQuery('#popup').show();
}
jQuery(window).unbind();
}
jQuery('#popupClose').click(function() {
jQuery('#popup').hide();
});
}
I want the popup to not repopulate after they click #popupClose.
I'd do it like this. Just define a start time when you initialize your script. Let an interval run that checks how much time has passed. If it's more than your time wished show the dialog. if not hide it. Also reset the timer on your events.
Your javascript will look like this
$('#btclose').on('click', function(){
clearInterval(interv);
$('#popup').hide();
});
var start = new Date();
var interv = setInterval(function(){
var now = new Date();
console.log()
if(now-start > 5*1000){
$('#popup').show();
}
},10);
$('body').on('mousedown click mousemove', function(){
start = new Date();
});
Here's my fiddle
https://jsfiddle.net/c2L7wpn3/8/
Seems to work. Let me know if this helps
You can either store the information in a cookie, or with a flag (depending on whether you want the popup on each pageview or only once, period).
Then, check the flag/cookie before the showing of the popup. For example:
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime >= 1) {
if (jQuery('#popup').data('closed') == 1){
jQuery('#popup').show();
}
}
jQuery(window).unbind();
}
jQuery('#popupClose').click(function() {
jQuery('#popup').data('closed', 1);
jQuery('#popup').hide();
});

jquery fire event after timeout

I've implemented auto page scrolling using the jQuery plugin datatables.
I'm attempting to add two buttons, one that stops the auto scrolling and one that starts it again. I've gotten this working, but I want it to begin scrolling again if the page has been stopped for a period of time. Here is what I have tried:
var refreshRate = 5;
var totalPages = 0;
var currentPage = 0;
var upTime = 0;
$('document').ready(function(){
var interval = window.setInterval('$("#start").click()',refreshRate);
$("#start").click(function(){
function start(){
clearInterval(timeout);
$("#stop").show();
$("#start").hide();
currentPage = table.api().page.info().page + 1;
totalPages = table.api().page.info().pages;
table.api().ajax.reload(function(json){
if (currentPage != totalPages){
table.api().page('next').draw(false);
}
else{
table.api().page('first').draw(false);
}
});
upTime = upTime + (refreshRate / 1000);
clearInterval(interval);
interval = setInterval('$("#start").click()', refreshRate);
}
start();
});
$("#stop").click(function(){
$("#stop").hide();
$("#start").show();
timeout();
clearInterval(interval);
});
//call start on doc ready to auto start scrolling
start();
function timeout(){
var timeout = window.setInterval(function(){
start();
}, 10000);
}
});
As you can see I am attempting to call the start() function embedded within the button click after a 10 second timeout. I am also getting a TypeError when I call start() at DOM ready to begin page scrolling.
Uncaught TypeError: object is not a function
But besides the error it scrolls as it should.
Any assistance?
You are having issues with function scope. Your code that called start towards the bottom did not have start in its scope since you defined it inside the click handler. Also, timeout was outside of the scope too, which would cause the interval to go on forever:
$('document').ready(function(){
var timeout,
interval = window.setInterval('$("#start").click()',refreshRate);
function start(){
clearInterval(timeout);
$("#stop").show();
$("#start").hide();
currentPage = table.api().page.info().page + 1;
totalPages = table.api().page.info().pages;
table.api().ajax.reload(function(json){
if (currentPage != totalPages){
table.api().page('next').draw(false);
}
else{
table.api().page('first').draw(false);
}
});
upTime = upTime + (refreshRate / 1000);
clearInterval(interval);
interval = setInterval('$("#start").click()', refreshRate);
}
function timeout(){
timeout = setInterval(function(){
start();
}, 10000);
}
$("#start").click(function(){
start();
});
$("#stop").click(function(){
$("#stop").hide();
$("#start").show();
timeout();
clearInterval(interval);
});
//call start on doc ready to auto start scrolling
start();
});

How to stop my javascript countdown?

How can I stop my javascript function when countdown = 0?
JS:
var settimmer = 0;
$(function(){
window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
}, 1000);
});
HTML:
<b id="show-time">20</b>
For one thing remove those evals. They don't do anything.
Then all you have to do is clear the timer when it reaches zero.
$(function(){
var timer = setInterval(function() {
var timeCounter = parseInt($("b[id=show-time]").text());
$("b[id=show-time]").text(--timeCounter); // remove one
if(!timeCounter) clearInterval(timer);
}, 1000);
});
It is easy! When you call setInterval it return an ID, so you can destroy the interval later. To destroy it you must use clearInterval(id), and voilà!
It works like this:
// Activate timer
var iv = window.setInterval(...);
// Deactive timer
window.clearInterval(iv);
Also you should use parseInt() instead of eval():
$(function() {
// Read the start value once and store it in a variable
var timeCounter = parseInt( $("b[id=show-time]").text() );
// Active the counter
var iv = window.setInterval(function() {
// Decrement by one and write back into the document
$("b[id=show-time]").text(--timeCounter);
// Check if counter == 0 -> stop counting
if (0 == timeCounter) {
window.clearInterval(iv);
// ...do whatever else needs to be done when counter == 0 ..
}
}, 1000);
});
Example:
var i = 0,
pid = setInterval(function() {
if (++i > 10)
clearInterval(pid);
}, 1000);
Based on what you wanted for your code ...
$(function() {
var el = document.getElementById('show-time'),
pid = setInterval(function() {
// (s - i) coerces s to Number
var t = el.innerHTML - 1;
el.innerHTML = t;
if (t < 1)
clearInterval(pid);
}, 1000);
});
Keep in mind that JS won't be 100% accurate with its timing.
Pasted code below or see the fiddle: http://jsfiddle.net/raHrm/
<script type="text/javascript">
$(function(){
var settimmer = 0,
timeCounter = $("#show-time").html(),
updateTime = timeCounter;
(function countDown() {
timeCounter = $("#show-time").html();
updateTime = parseInt(timeCounter)-1;
$("#show-time").html(updateTime);
if ( updateTime ) {
setTimeout(countDown, 1000);
}
})();
});​
</script>
Set the timer to a variable, then use clearInterval in-order to stop the loop. As for catching the end, use a simple conditional:
$(function(){
var elem=$('strong[id="show-time"]'),settimmer=0,updateTime,t;
t=window.setInterval(function() {
updateTime=parseFloat(elem.html(),10)-1;
if(updateTime==0) {
window.clearInterval(t);
elem.html('Done!');
} else {
elem.html(updateTime);
}
},1000);
});
Then in the HTML:
<strong id="show-time">20</strong>
The <b> tag is depreciated, try to avoid using it. Also, there is no reason to eval() the HTML you are getting from the element; a simple parseFloat() works just fine.

Categories