I am working on an application which requires to logout itself after certain amount of time, if user is not active on the page. I am using azure authentication token, and it expires in One hour. Now here I am trying to setup two timers, first timer will run every one min and will keep on resetting itself with every mouse action, and the 2nd timer should load after 58 mins of inactive, showing there are only 120 seconds remaining in the session. I am unable to get desired the functionality, the first timer runs after 1 min, but simultaneously it also kicks of the second timer.
Here's my Javascript code..
<script>
function timerModal() {
var count = 120;
console.log("This has started");
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
count = count - 1;
if (count <= 0) {
$(this).mousemove(function (e) {
count = 120;
});
$(this).keypress(function (e) {
count = 120;
});
clearInterval(counter);
//vmsWebUtils.signOut(); //counter ended, do something here
return;
}
document.getElementById("timer").innerHTML = count + " "; // watch for spelling
console.log(count);
}
}
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime => 57) { // 57 minutes
$("#sessionTimeout").show();
timerModal();
}
console.log(idleTime);
}
</script>
I required the same effect for a site once, here is the code if it helps. (it's set to immediately show the prompt for testing purposes)
$('input').keypress(function(e) {
if (e.which == 13) {
$(this).next('input').focus();
e.preventDefault();
}
resetlogout();
});
$('textarea').keypress(function(e) {
resetlogout();
});
var autolog1 = setTimeout("logmeoutmsg()", 1);
var autolog = setTimeout("logmeout()", 10000);
function logmeout() {
window.location.href = "index.php?logout=1";
}
function logmeoutmsg() {
$("#logoutmsg").show();
var count=10;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
timer();
function timer()
{
$("#counterdown").html(count);
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
}
}
function resetlogout() {
clearTimeout(autolog1);
clearTimeout(autolog);
autolog1 = setTimeout("logmeoutmsg()", 1);
autolog = setTimeout("logmeout()", 10000);
$("#logoutmsg").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="logoutmsg" style="display:none;position:fixed;left:50%;top:100px;margin-left:-400px;border:1px solid #2e2e2e;width:800px;background:#eedbba;padding:10px 0px;">
<div style="width:760px;margin-left:20px;text-align:center;">
You will be logged out in <div style="display:inline-block;" id="counterdown"></div> seconds.<br><input style="color:#0000ff;cursor:pointer;" type="button" onclick="resetlogout();" value="Cancel">
<input style="color:#0000ff;cursor:pointer;" type="button" onclick="resetlogout();" value="Logout">
</div>
</div>
I fixed it my self with some modifications, here's the modified code !!
Works perfectly fine!!
<script>
var idleTime = 0;
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
function timerIncrement() {
idleTime = idleTime + 1;
console.log(idleTime);
if (idleTime > 2) { // 57 minutes
clearInterval(idleInterval);
timerModal();
console.log("hello");
}
console.log(idleTime);
}
function timerModal() {
var count = 120;
console.log("This has started");
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
vmsWebUtils.signOut(); //counter ended, do something here
return;
}
document.getElementById("timer").innerHTML = count + " "; // watch for spelling
console.log(count);
}
}
</script>
Related
I'm a complete newb to javascript, and much of this code was pulled from other sites. I'm trying to use two things I found to make a page redirect after the user is inactive for a specified amount of time.
I was able to get the timer working and make the page reload instead of redirecting, but my redirect code doesn't work for some reason.
EDIT: forgot to mention this code needs to work for specific pages, as I will be using one page to redirect to a specific page, and another to a different page.
jQuery(document).ready(function( $ ){
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 10000); // 10 seconds
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if ((idleTime > 0) && (window.location.pathname == '/wp')) { // 10 seconds
window.location.href = "https://www.google.com";
}
}
});
I tried you code, it works, but wrong. If it don't work for you - remove that && (window.location.pathname == '/wp') and try again. You have bigger problem, your code just redirects after 10 seconds no matter what. You need to replace to something like that:
jQuery(document).ready(function( $ ){
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 1000); // 1 second
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if ((idleTime > 9) && (window.location.pathname == '/wp')) { // 10 seconds
window.location.href = "https://www.google.com";
}
}
});
I have a button its disabled and i want to put a counter inside it, what i want to do is when the counter reaches zero it get enabled, how can i do that? in the code below the counter doesn't appear inside the button and i don't want the reset button i just want the button to be enabled when it reaches zero, here is what i have tried so far:
function Countdown()
{
this.start_time = "00:30";
this.target_id = "#timer";
this.name = "timer";
this.reset_btn = "#reset";
}
Countdown.prototype.init = function()
{
this.reset();
setInterval(this.name + '.tick()',1000)
}
Countdown.prototype.reset = function()
{
$(this.reset_btn).hide();
time = this.start_time.split(":");
//this.minutes = parseInt(time[0]);
this.seconds = parseInt(time[1]);
this.update_target();
}
Countdown.prototype.tick = function()
{
if(this.seconds > 0) //|| this.minutes > 0)
{
if(this.seconds == 0)
{
// this.minutes = this.minutes - 1;
this.seconds = 59
} else {
this.seconds = this.seconds - 1;
}
}
this.update_target()
}
Countdown.prototype.update_target = function()
{
seconds = this.seconds;
if (seconds == 0) $(this.reset_btn).show();
else if(seconds < 10) seconds = "0" + seconds;
$(this.target_id).val(this.seconds)
}
timer = new Countdown();
timer.init();
$(document).ready(function(){
$("#reset").click(function(){
//timer = new Countdown();
timer.reset();
});
});
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="text" id="timer" disabled>Counter should be inside me, and enable me when it reaches 0</button>
<button id="reset">Reset</button>
This is much simpler than what you've got. Just use window.setTimeout().
Keep in mind that tracking time to a high precision is not super reliable in a browser. You may want to look at moment.js or use performance.now() for an easier API to handle that.
// Get refreence to span and button
var spn = document.getElementById("count");
var btn = document.getElementById("btnCounter");
var count = 5; // Set count
var timer = null; // For referencing the timer
(function countDown(){
// Display counter and start counting down
spn.textContent = count;
// Run the function again every second if the count is not zero
if(count !== 0){
timer = setTimeout(countDown, 1000);
count--; // decrease the timer
} else {
// Enable the button
btn.removeAttribute("disabled");
}
}());
<button id="btnCounter" disabled>Time left: <span id="count"></span></button>
var secondsP = document.getElementById('seconds');
var btn1 = document.getElementById("btnSurrender");
var clock = null;
btn1.addEventListener("click", surrender);
function timer () {
clearInterval(clock);
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
}
if (seconds === 0) {
}
}, 1000);
}
function surrender(){
clearInterval(clock);
secondsP.textContent = 0;
setTimeout(timer,2000);
}
timer();
setInterval(timer, 17000);
<html>
<head>
<style>
</style>
<script src="/scripts/snippet-javascript-console.min.js?v=1"></script>
</head>
<body>
<p id="seconds">15</p>
<button id= "btnSurrender">end now</button>
</body>
</html>
I need help with my little problem. I made a stopwatch which counts down 15 seconds. After this 15 seconds, it waits two seconds and starts again. You have option to stop counting when you want to, using "end now" button (then it'll start again after 2 sec). Now, my question is: how can I make a function which is going to stop whole counting after 3/4 rounds?
You restart the clock in surrender() using the call setTimeout(timer, 2000). All you need to do is add an if statement inside that function testing a variable that controls how many times you have run the timer, and then call/not call timer() accordingly. Here is a working example of it: https://jsfiddle.net/L38q6k5d/, but just to give you an idea of how it would work:
At the top of the js file:
var timesRun = 0
var timerInterval = null;
Inside the surrender function:
timesRun += 1 // Increment it each time the timer ends
if (timesRun > 4) { // If the timer has run less than 4 times
return; // this will stop the function here, so we dont start the timer again
}
setTimeout(timer, 2000); // Reset the timer
Inside the timer function,
if (timesRun > 1) {
clearInterval(timerInterval);
return; // end the function here
}
When starting the initial timer:
timer();
timerInterval = setInterval(timer, 17000);
Complete JS:
var secondsP = document.getElementById('seconds');
var btn1 = document.getElementById("btnSurrender");
var clock = null;
var timerInterval = null;
// New Code
var numberOfTimesRun = 0; // this is where we keep track of how many times the timer has run
btn1.addEventListener("click", surrender);
function timer () {
clearInterval(clock);
// New Code
if (numberOfTimesRun > 1) {
clearInterval(timerInterval);
return; // end the function here
}
// End New Code
var start = new Date().getTime();
clock = setInterval(function() {
var seconds = Math.round(15 - (new Date().getTime() - start) / 1000);
if (seconds >= 0) {
secondsP.textContent = seconds;
} else {
clearInterval(clock);
numberOfTimesRun += 1; // so we know that 1 iteration of the timer has been completed
}
if (seconds === 0) {
}
}, 1000);
}
function surrender(){
clearInterval(clock);
secondsP.textContent = 0;
//New Code
numberOfTimesRun += 1;
if (numberOfTimesRun > 4) {
return; // end the function there
}
setTimeout(timer, 2000)
//End New Code
}
timer();
timerInterval = setInterval(timer, 17000);
I have javascript countdown timer from 25 -> 0.
var count=25;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
function timer()
{
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count; // watch for spelling
}
div HTML
<span id="timer">25</span>
Now I want the countdown is repeat automatically after wait 5 seconds then it start again from 25 -> 0. And I want to count how many times that countdown repeat. Is it possible for that?
Please help.
You can try wrapping the entire code into a function (countTimers() in the example below) that runs every 30 seconds (5 seconds after each timer). Then, set a counter (timersCount in the example below) to count how many times that will run.
See the example below:
var timersCount = 0, stopped = false, count, counter; // make count, counter global variables so buttons can access them
var timerCounter = setInterval(countTimers, 30000);
countTimers(); // run countTimers once to start
function timer() {
count = count-1;
document.getElementById("timer").innerHTML=count;
if(count <= 0) {
clearInterval(counter);
return;
}
}
function countTimers() {
timersCount++;
// as per request in the comments, you can set a timer counter as well:
document.getElementById("totalcounter").innerHTML = timersCount;
count = 25;
counter = setInterval(timer, 1000);
}
// button code:
document.getElementById("reset").addEventListener("click", function() {
clearInterval(timerCounter);
clearInterval(counter);
count = 25;
document.getElementById("timer").innerHTML=count;
timersCount = 0;
document.getElementById("totalcounter").innerHTML = timersCount;
stopped = true;
});
document.getElementById("stop").addEventListener("click", function() {
if(stopped)
return;
clearInterval(counter);
stopped = true;
});
document.getElementById("start").addEventListener("click", function() {
if(!stopped)
return;
stopped = false;
counter = setInterval(timer, 1000);
setTimeout(function() {
clearInterval(counter);
timerCounter = setInterval(countTimers, 30000);
countTimers();
}, count*1000);
});
Timer: <span id="timer">25</span><br>
Number of times run: <span id="totalcounter">1</span>
<br><br>
<button id="reset">Reset</button>
<button id="stop">Stop</button>
<button id="start">Start (if stopped)</button>
var count=25;
var counter = null;
// reset count and timer
function reset_timer()
{
count = 25;
counter=setInterval(timer, 1000); //1000 will run it every 1 second
}
// init timer for first time
reset_timer();
function timer()
{
count--;
if (count <= 0)
{
clearInterval(counter);
setTimeout(reset_timer, 5000);
return;
}
document.getElementById("timer").innerHTML=count; // watch for spelling
}
setTimeout is a timer that runs one time and stop.
This approach uses Promises to the countdown work and generate an infinite loop,
if for some reason you need to stop/resume your counter you can reject the Promise chain and have a boolean to control the state:
let secondsCounter =
document.querySelector('#secondsCounter'),
totalCount =
document.querySelector('#totalCount'),
ttc = 1,
actualSecond = 25,
isPaused = false,
interval;
let countDown = time => new Promise( (rs, rj) => interval = setInterval( ()=>{
if (isPaused) {
return rj('Paused');
}
secondsCounter.textContent = --actualSecond;
if (actualSecond == 0){
actualSecond = time + 1;
clearInterval(interval);
rs();
}
}, 1000));
let loop = time => countDown(time).then( ()=>{
totalCount.textContent = ++ttc;
return Promise.resolve(null);
});
let infinite = () => loop(25)
.then(infinite)
.catch(console.log.bind(console));
let stop = () => {
clearInterval(interval);
isPaused = true;
}
let resume = () => {
console.log('Resumed');
isPaused = false;
loop(actualSecond).then(infinite);
}
let start_stop = () => isPaused ?
resume() : stop();
infinite();
Seconds : <div id="secondsCounter">25</div>
Times : <div id="totalCount">1</div>
<button onclick="start_stop()">Start/Stop</button>
i have this function in Idle library, but what i need is to calculate the action time in second, i mean the active time(onclick, onscroll and keypress).
function is:
(function () {
var minutes = false;
var interval = 1000;
var IDLE_TIMEOUT = 5;
var idleCounter = 0;
var counter=0;
document.onclick = document.onkeypress = function () {
idleCounter = 0;
setInterval(function () {
++counter;;
}, 1000);
};
window.setInterval(function () {
if (++idleCounter >= IDLE_TIMEOUT) {
alert(counter);
document.location.href = "SessionExpired.aspx";
}
}, interval);
}());
this function will wait for 5 seconds, if no action on the page, so i will be redirected to SessionExpired.aspx. if there is action, so am doing ++couter each second.
I need when this counter in seconds.
Thank you.
You can just reset the timer
var counter;
var counterSeconds;
document.onclick = document.onkeypress = function () {
idleCounter = 0; // Set counter to 0 on each keypress/page click
clearInterval(counter) // Every time they click, clear the old interval and start a new one below
counter = setInterval(function () { // assign the interval to a variable so we can clear it
if (idleCounter > IDLE_TIMEOUT) { // Check if they've idled too long
document.location.href = "SessionExpired.aspx"; // Redirect them if they have
}
++counterSeconds;
++idleCounter; // Should increment 1/sec depending on your computer.
}, 1000); // Ticks at 1000 milliseconds (1 Second)
};
One problem here is that you start new interval function for each click or keypress event which causes multiple threads to update same variable.
You should start an interval thread outside the event.
try this:
document.onclick = document.onkeypress = function () {
idleCounter = 0;
};
var activeTimer = setInterval(function () {
++counter;
}, interval);
var idleTimer = window.setInterval(function () {
if (++idleCounter >= IDLE_TIMEOUT) {
alert(counter);
document.location.href = "SessionExpired.aspx";
}
}, interval);
This is what i wanted exactly and i did it:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" ></script>
<script src="./e-lawyer/JS/idle.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>timertest</title>
<script language="javascript">
var it;
x = 0;
$(document).ready(function(){
$('.status').html('active');
});
function count() {
x+=1;
$('.usercount').html(x);
}
(function() {
var timeout = 2000;
$(document).bind("idle.idleTimer", function() {
clearInterval(it);
$('.status').html('idle');
});
$(document).bind("active.idleTimer", function() {
it = setInterval(count, 1000);
$('.status').html('active');
});
$.idleTimer(timeout);
})(jQuery);
</script>
</head>
<body>
<div class="status" style="border:1px dashed black; width:500px; height:50px;"></div>
<div class="usercount"style="border:1px dashed black; width:500px; height:50px;"></div>
</body>
</html>