jquery fire event after timeout - javascript

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();
});

Related

Pure JavaScript: How to refresh page after countdown if the browser tab is active

I want to achieve the following scenario:
Set a timer of 60 seconds and start the countdown displaying the
timer. After the countdown is finished, refresh (not reload) the page
and restart the countdown timer and continue the process.
If the browser's tab is changed, after finishing the timer, refresh the
page and pause the timer, and only when the tab is active again refresh
the page and start the countdown timer again.
I have managed to achieve the first requirement like:
Result will Refresh in <span id="countdown"></span>
<script>
if (!document.hidden) {
function timedRefresh(e) {
var n = setInterval((function () {
e > 0 ? (e -= 1, document.getElementById("countdown").innerHTML = e) : (clearInterval(n), window.location.reload())
}), 1e3)
}
timedRefresh(59)
}
</script>
And is unable to achieve the second requirement. I have tried to implement the solution mentioned here: Is there a way to detect if a browser window is not currently active?
But it didn't work.
How do I achieve the requirements in pure JavaScript code?
The following code has solved this scenario. It's a little messy, but I think is understandable. We use both window.document.hasFocus() and the focus event to create this solution. I have changed the window.location.reload() methods to just consoles simulating a function that refresh the data inside the application, since is asked to us refresh (not reload).
function timedRefresh(intervalTime) {
let interval = null;
let currentTime = intervalTime;
const updateTimer = () => {
const countdownSpan = document.getElementById("countdown");
if (currentTime <= 0) {
console.log(`print refresh at ${new Date()}`); // refresh page
if (window.document.hasFocus()) {
currentTime = intervalTime;
} else {
clearInterval(interval);
interval = null;
currentTime = intervalTime;
}
}
if (!interval) {
countdownSpan.innerHTML = "#";
} else {
countdownSpan.innerHTML = currentTime;
currentTime -= 1;
}
};
interval = setInterval(updateTimer, 1000);
window.addEventListener("focus", () => {
if (!interval) {
interval = setInterval(updateTimer, 1000);
}
});
}
const TIMER_SECONDS = 5;
timedRefresh(TIMER_SECONDS);
Edit:
The answer above does not work with reloads using window.location.realod(). A code solving the issue may look like this:
const TIMER_SECONDS = 60;
/*
* Update span with current time
* `currentTime` is an integer bigger than zero or a string '#' meaning 'timer stopped'
*/
function updateDisplayTimer(currentTime){
const countdownSpan = document.getElementById("countdown");
countdownSpan.innerHTML = currentTime;
}
/*
* A timer with `loopDuration` seconds. After finished, the timer is cleared.
* `loopDuration` is an integer bigger than zero, representing the time duration in seconds.
*/
function timedRefresh(loopDuration) {
let currentTime = loopDuration;
let interval = setInterval(() => {
if (currentTime > 0) {
updateDisplayTimer(currentTime);
currentTime -= 1;
} else {
window.location.reload(); // refresh page
}
}, 1000);
window.addEventListener('load', () => {
if(window.document.hasFocus()){
timedRefresh(TIMER_SECONDS);
} else {
updateDisplayTimer("#");
clearInterval(interval);
interval = null;
}
});
window.addEventListener('focus', () => {
if(interval == null){
window.location.reload(); // refresh page
}
});
}
// exeute main fucntion
timedRefresh(TIMER_SECONDS);
Use window.document.hasFocus() to determine if the user is focused on your webpage or not.

Countdown won't stop at 0, keeps decrementing

I have a timer that keeps decrementing after 0 so I get negative numbers. Time starts when a button is clicked and the pauses when the same button is clicked again.
button.addEventListener("click", function(event){
console.log('timer started')
// Timer paused, click to start
// Pause/Play Timer
if(timeleft == 90){
timeleft = setInterval(function() {
time--;
timerDisplay.innerHTML = time;
}, 1000);
} else if (timeleft === 0) {
clearInterval(timeleft);
} else{
// Timer running, click to pause
console.log('timer paused')
clearInterval(timeleft);
timeleft = 90;
}
});
The stop and start functionality works fine but why won't it stop counting down once it reaches 0?
Sample code for reference to build a timer.
const actionBtn = document.getElementById("start-timer");
let isTimerRunning = false;
let interval = null;
let maxTime = 20;
// Click handler to start and stop timer button in DOM
actionBtn.addEventListener("click", function() {
if(isTimerRunning) {
// stop timer
stopTimer();
} else {
// start timer
startTimer();
}
});
// Function to start timer
function startTimer() {
isTimerRunning = true; // toggle state, so on click again we can stop timer
// 1sec interval function to reduce max time
interval = setInterval(function() {
maxTime = maxTime - 1;
if(maxTime > -1) { // if the more time left (more than 0) update UI
renderUi(`Reset (${maxTime}sec)`);
} else { // if there is no time left stop timer
stopTimer();
}
}, 1000);
}
// stop timer
function stopTimer() {
isTimerRunning = false; // toggle state, so on click again we can start timer
clearInterval(interval); // clear the interval
maxTime = 20; // reset max time to initial value
renderUi(`Start Timer (${maxTime}sec)`); // update UI to initial value
}
// A generic function to update UI
// if we have complet UI structure we can update this function
function renderUi(str) {
actionBtn.innerText = str;
}
<button id="start-timer">Start Timer (20sec)</button>

Javascript - page reload script won't work

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";
}
}
});

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();
});

How to reset session on keypress

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
}

Categories