Start timer every 1 minute Jquery - javascript

Trying to start my timer if the app is in idle start for 1 minute.
My timer is starting initially, how do I check whether my app is idle or not.
And also if the timer starts and interrupts in between then the timer should disappear and stay on the same page.
else redirect to home page.
JS:
var interval = setInterval(function() {
var timer = $('span').html();
var seconds = parseInt(timer,10);
seconds -= 1;
if (seconds < 0 ) {
seconds = 59;
}
else if (seconds < 10 && length.seconds != 2) seconds = '0' + seconds;
$('span').html(seconds);
if (seconds == 0)
clearInterval(interval);
}, 1000);
This is what I have tried:
Demo

$(document).ready(function(){
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
idleTime = 0;
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
//after every one minute this function will call and it check idleTime is
//increment if it is one then reload the page
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 1) { // 1 minutes
//alert();
window.location.reload();
}
}

Related

swal alert after 10 minutes of inactivity

How can I make a swal alert that gets triggered after 10 minutes of inactivity on my laravel app?
Also, there should be a logout button in the swal alert. Is it possible?
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 > 10) { // ten minute
alert("enter your html code for logout")
}
}

Why is Javascript clearInterval not working on button click?

I have a timer program that counts down from 25:00 on "start" button click and is supposed to reset and clearInterval() on "reset" button click. When the timer reaches 0:00 the if statements all pass and resetTimer() is called which executes the clearInterval() which works in this instance. So in short: clearInterval() works when the if statements pass but not when I click the "reset" button. Can someone please explain to me why this is happening and offer a solution? Thank you!
//My Programs Code:
//Timer Widget
function timerStartReset(event) {
var minutes;
var seconds;
//decrease minutes html every minute
const minutesInterval = setInterval(() => {
minutes -= 1;
timerMinute.innerHTML = minutes;
}, 60000);
//decrease seconds html every second
const secondsInterval = setInterval(() => {
seconds -= 1;
timerSeconds.innerHTML = seconds < 10 ? `0${seconds}` : seconds;
//check if timer reaches 00:00
if (seconds <= 0) {
if (minutes <= 0) {
//stop and reset timer
//**HERE resetTimer() is called and clearInterval works**
resetTimer();
//return start button functionality
timerStartBtn.disabled = false;
//add a star
const addStar = `<i class="fas fa-star h2 mx-2"></i>`;
timerStarContainer.insertAdjacentHTML("beforeend", addStar);
localStorage.setItem("timer stars", timerStarContainer.innerHTML);
setTimeout(breakAlert, 1000);
}
seconds = 60;
}
}, 1000);
//start button function
if (event.target.id === "timer-start") {
startTimer();
event.target.disabled = true;
}
//reset button function
else {
//**HERE resetTimer() is called but clearInterval doesn't work**
resetTimer();
timerStartBtn.disabled = false;
}
//Reset timer
function resetTimer() {
//Reset to starting template
timerMinute.innerHTML = 25;
timerSeconds.innerHTML = "00";
//Clear minute/second timeout function
clearInterval(minutesInterval);
clearInterval(secondsInterval);
}
//start timer
function startTimer() {
//Change starting time and add them to page
minutes = 0;
seconds = 1;
timerMinute.innerHTML = minutes;
timerSeconds.innerHTML = seconds;
//start countdown
minutesInterval;
secondsInterval;
}
//Alert for breaks
function breakAlert() {
//If 4 star divs are added dynamically
if (timerStarContainer.childElementCount >= 4) {
swal(
"Great Job! You Did It!",
"Go ahead and take a 15-30 minute break!",
"success"
);
//remove all stars from DOM
timerStarContainer.innerHTML = "";
} else {
swal("Awesome!", "Please take a 5 minute break!", "success");
}
}
}
//End Timer Widget
const timerMinute = document.querySelector("#minute");
const timerSeconds = document.querySelector("#seconds");
const timerStartBtn = document.querySelector("#timer-start");
document.querySelector("#timer-btns").addEventListener("click", timerStartReset);
//Timer Widget
function timerStartReset(event) {
var minutes;
var seconds;
//decrease minutes html every minute
const minutesInterval = setInterval(() => {
minutes -= 1;
timerMinute.innerHTML = minutes;
}, 60000);
//decrease seconds html every second
const secondsInterval = setInterval(() => {
seconds -= 1;
timerSeconds.innerHTML = seconds < 10 ? `0${seconds}` : seconds;
//check if timer reaches 00:00
if (seconds <= 0) {
if (minutes <= 0) {
//stop and reset timer
resetTimer();
//return start button functionality
timerStartBtn.disabled = false;
}
seconds = 60;
}
}, 1000);
//start button function
if (event.target.id === "timer-start") {
startTimer();
event.target.disabled = true;
}
//reset button function
else {
resetTimer();
timerStartBtn.disabled = false;
}
//Reset timer
function resetTimer() {
//Reset to starting template
timerMinute.innerHTML = 0;
timerSeconds.innerHTML = 11;
//Clear minute/second timeout function
clearInterval(minutesInterval);
clearInterval(secondsInterval);
console.log("reset");
}
//start timer
function startTimer() {
//Change starting time and add them to page
minutes = 0;
seconds = 10;
timerMinute.innerHTML = minutes;
timerSeconds.innerHTML = seconds;
//start countdown
minutesInterval;
secondsInterval;
}
}
//End Timer Widget
<!-- Timer -->
<div>
<span id="minute">0</span>
<span>:</span>
<span id="seconds">11</span>
</div>
<div id="timer-btns">
<button id="timer-start">Start</button>
<button id="timer-reset">Reset</button>
</div>
<!-- End Timer -->
The variables minutesInterval and secondsInterval are local to this function. So every time you call the function, it starts new timers and creates new variables. When the code calls resetTimer(), it's only resetting the timer started by that invocation of timerStartReset, not the previous ones.
It works when the timer runs out, because the countdown code is in the same scope. But when you click the Reset button, that function is a new scope and can't access the variables from when the Start button was clicked.
The timer variables should be global variables that can be accessed from any invocation. And then there's no reason to use the same function for both buttons.
var minutesInterval;
var secondsInterval;
timerStartBtn.addEventListener('click', timerStart);
timerResetBtn.addEventListener('click', resetTimer);
function timerStart() {
resetTimer();
var minutes;
var seconds;
//decrease minutes html every minute
minutesInterval = setInterval(() => {
minutes -= 1;
timerMinute.innerHTML = minutes;
}, 60000);
//decrease seconds html every second
secondsInterval = setInterval(() => {
seconds -= 1;
timerSeconds.innerHTML = seconds < 10 ? `0${seconds}` : seconds;
//check if timer reaches 00:00
if (seconds <= 0) {
if (minutes <= 0) {
resetTimer();
//return start button functionality
timerStartBtn.disabled = false;
//add a star
const addStar = `<i class="fas fa-star h2 mx-2"></i>`;
timerStarContainer.insertAdjacentHTML("beforeend", addStar);
localStorage.setItem("timer stars", timerStarContainer.innerHTML);
setTimeout(breakAlert, 1000);
}
seconds = 60;
}
}, 1000);
startTimer();
//start timer
function startTimer() {
//Change starting time and add them to page
minutes = 0;
seconds = 1;
timerMinute.innerHTML = minutes;
timerSeconds.innerHTML = seconds;
//start countdown
minutesInterval;
secondsInterval;
}
//Alert for breaks
function breakAlert() {
//If 4 star divs are added dynamically
if (timerStarContainer.childElementCount >= 4) {
swal(
"Great Job! You Did It!",
"Go ahead and take a 15-30 minute break!",
"success"
);
//remove all stars from DOM
timerStarContainer.innerHTML = "";
} else {
swal("Awesome!", "Please take a 5 minute break!", "success");
}
}
}
//Reset timer
function resetTimer() {
//Reset to starting template
timerMinute.innerHTML = 25;
timerSeconds.innerHTML = "00";
//Clear minute/second timeout function
clearInterval(minutesInterval);
clearInterval(secondsInterval);
}
//End Timer Widget

How to catch events to clear cookies?

I have developed a login page. I am saving sessionId in local storage on login and I want to clear it after some time. But that to be if someone(logged-user) not active for some time. If he is active, I don't want to clear. But I did that even he is active also, I am clearing the local storage. Please help to know how to catch he is active or not.
localStorage.setItem('userId', data.id);
localStorage.setItem('user', data.phone);
localStorage.setItem('sessionId', (Math.random()*1e64).toString(36));
var interval = setInterval(function(){
console.log('In localStorage');
localStorage.removeItem('sessionId');
clearInterval(interval);
alert('Session expired!!')
}, (30*60*1000));
You can just check use a setInterval:
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 > 19) { // 20 minutes
localStorage.removeItem('sessionId');
}
}
Answer borrowed from here

Using system clock for accurate idle timeout warning

I am working on a modal which will alert users of a pending logout due to idle time. Overall it works, but I notice the timer is not 100% accurate. I know there are issues with setInterval and accuracy. I still seeing discrepancies and will welcome a suggestion on how to improve my code.
var sessionTimeoutPeriod = 240;
var state = "L";
var timeoutPeriod = sessionTimeoutPeriod * 1000;
var logout = Math.floor(timeoutPeriod / 60000);
var idleInterval;
if (state == "L" || state == "O" || state == "C") {
var idleTime = 0;
$(document).ready(function() {
//Zero the idle timer on mouse movement.
$(this).mousemove(function(e) {
idleTime = 0;
console.log("The mouse moved, idle time = " + idleTime);
});
$(this).keypress(function(e) {
idleTime = 0;
console.log("A key was pressed, idle time = " + idleTime);
});
idleInterval = setInterval(timerIncrement, 60000); // 1 minute
});
function timerIncrement() {
idleTime++;
console.log("The total idle time is "+idleTime+ " minutes.");
if (idleTime >= 1) {
console.log("The modal will fire if idle time = " +idleTime);
var modal = new window.AccessibleModal({
mainPage: $('#main'),
overlay: $('#overlay').css('display', 'block'),
modal: $('#modal-session-timeout'),
prevFocus: $('#main')
});
modal.show();
$('#modal-overlay').removeClass('opened');
$('.js-timeout-refresh, .xClose').click(function() {
modal.hide();
$('#overlayTY').css('display', 'none');
idleTime = 0;
console.log("The total idle time is "+idleTime+ " minutes.");
});
$('.js-timeout-session-end').click(function() {
modal.hide();
$('#overlay').css('display', 'none');
endSession();
});
console.log(idleTime);
}
if (idleTime == logout) { // 9 minutes
endSession();
}
var endSession = function() {
document.location.replace(logoutPageUrl);
};
}
}
Instead of relying on the interval to determine how much time has passed, you could validate how much time has passed manually by comparing the current time against the time since last activity.
This way you can increase the checking interval without having to modify the code. The discrepancy will never be higher then then the interval timeout now, the discrepancy will also not change incrementally, it will always be lower or equal to the interval ( in worst case scenario ).
Here is a basic example.
var sessionTimeoutPeriod = 240;
var timeoutPeriod = sessionTimeoutPeriod * 1000;
var oneMinute = 60000;
var showIdlePopUpTimeOut = oneMinute * 2;
var lastActivity = new Date();
function getIdleTime() {
return new Date().getTime() - lastActivity.getTime();
}
$(document).ready(function () {
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
console.log("The mouse moved, idle time = " + getIdleTime());
lastActivity = new Date();
});
$(this).keypress(function (e) {
console.log("A key was pressed, idle time = " + getIdleTime());
lastActivity = new Date();
});
setInterval(checkIdleTime, 5000);
});
function endSession() {
document.location.replace(logoutPageUrl);
};
function checkIdleTime() {
var idleTime = getIdleTime();
console.log("The total idle time is " + idleTime / oneMinute + " minutes.");
if (idleTime > showIdlePopUpTimeOut) {
var modal = new window.AccessibleModal({
mainPage: $('#main'),
overlay: $('#overlay').css('display', 'block'),
modal: $('#modal-session-timeout'),
prevFocus: $('#main')
});
modal.show();
$('#modal-overlay').removeClass('opened');
$('.js-timeout-refresh, .xClose').click(function () {
modal.hide();
$('#overlayTY').css('display', 'none');
lastActivity = new Date();
});
$('.js-timeout-session-end').click(function () {
modal.hide();
$('#overlay').css('display', 'none');
endSession();
});
console.log(lastActivity);
}
if (idleTime > timeoutPeriod) { // 4 minutes
endSession();
}
}
The problem is that your function "timerIncrement" checks the difference every minute after loading the page, so you will never get exact 1 minute after last activity.Changing interval from 60000 to 1000 will solve the issue.
You don't even need to calculate diff, you can just reset timeout every time there is activity. like this:
$(this).on("mousemove keypress", function(e) {
clearInterval(idleInterval);
idleInterval = setTimeout(functionThatExecutesAfter1minInactivity, 60000);
});

setInterval recount?

var sec = 10
var timer = setInterval(function() {
$('#timer span').text(sec--);
if (sec == -1) {
clearInterval(timer);
} }, 1000);
html
<div id="timer"><span>10</span> seconds</div>
Recount
What I want to do when I click recount is to recount back to 10 seconds the timer?
How can I possibly done it?
It is better to use setInterval() or setTimeout()?
Factor out your code into functions so you can call the same code on startup or when the link is clicked. You can see it working here: http://jsfiddle.net/jfriend00/x3S7j/. This even allows you to click the link during the countdown and it will start over.
$("#recount").click(function() {
initCounter(10);
});
var remainingTime;
var runningInterval = null;
function initCounter(duration) {
function stopCounter() {
if (runningInterval) {
clearInterval(runningInterval);
runningInterval = null;
}
}
stopCounter(); // stop previously running timer
remainingTime = duration; // init duration
$('#timer span').text(remainingTime); // set initial time remaining
runningInterval = setInterval(function() { // start new interval
$('#timer span').text(remainingTime--);
if (remainingTime < 0) {
stopCounter();
}
}, 1000);
}
initCounter(10);
You can just add a click handler and factor out your code in a separate method:
var sec = 10;
var timer;
function startCountdown() {
if (timer) clearInterval(timer);
sec = 10;
timer = setInterval(function() {
$('#timer span').text(sec--);
if (sec == -1) {
clearInterval(timer);
}
}, 1000);
}
$(function() {
startCountdown();
$("#recount").click(startCountdown);
});
Working JSFiddle
When you click recount, you should
sec = 10;
clearInterval(timer);
timer = setInterval(that_function, 1000);
Also, there's a difference between setInterval and setTimeout. setInterval schedules the function to be called every some milliseconds. setTimeout schedules the function to be called once, after some milliseconds.

Categories

Resources