Andrew Andrew - 6 days ago 5
Javascript Question

Redirect with inactivity

My objective is to keep a user in a view as long as he/she keeps clicking a button within a certain lapse.

I'm using Rails and was exploring a solution via an embedded JS in the pertinent view.

So far I'm able to set a time after which the user will be redirected to root path with the following script:

var delayedRedirect = function (){
window.location = "/";
}

var delay = 10000;

$(document).ready(function() {
setTimeout('delayedRedirect()', delay);
});


I've been trying to write a function that resets the value of 'delay'or that calls the setTimeoutFunction again.

$('#btn-persist').click(function() {
delay = 3000;
// or calling again setTimeout('delayedRedirect()', delay);
});


But I noticed that changing the variable won't affect the setTimeout function that has already been called.

I've also tried to use the clearTimeout function as below without success

var delayedRedirect = function (){
window.location = "/persists";
}

var delay = 3000;

var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);
}

var stopRedirect = function (){
clearTimeout(triggerRedirect);
}

$(document).ready(function() {
triggerRedirect();

$('#btn-persist').click(function() {
stopRedirect();
});
});


I wonder why this may not be working and if there's any other way to stop the execution of the setTimeout function that has already been called so I can call it again to effectively reset the time to the original value of 'delay'.

At the same time, I don't want to stop any other JS functions that are running in parallel.

Do you see a better solution to achieve this?

Answer

The main problem why clearTimeout is not working. because you are clearing a anonymous function instead of a setTimeout variable

change this

var triggerRedirect = function() { setTimeout('delayedRedirect()', delay); 
}

to this

var triggerRedirect = setTimeout('delayedRedirect()', delay);

Edit: also change this (if you want to restart the inactive redirect trigger)

$('#btn-persist').click(function() {
    stopRedirect();
  });

to this

$('#btn-persist').click(function() {
        stopRedirect();
        triggerRedirect();
      });
Comments