Check for idle status in meteor by using ‘setInterval’

Posted on

Problem

I’m trying to check in my meteor app for a defined timeout (idle user) to show a modal. But the way I did it seems a bit too complicated to me.

I’m doing a setInterval for 1 minute. Then a counter – which is stored in a Session var (maybe a local reactive var would be smarter?) – will be incremented by one. If there is any event (mousemove, keypress and so on), the counter will be reset.

Template.example.onRendered(function() {
    Session.set('idleTime', 0);
    //Increment the idle time counter every minute.
    var idleInterval = setInterval(timerIncrement, 60000);

    function timerIncrement() {
        idleTime = Session.get('idleTime');
        idleTime = idleTime + 1;
        Session.set('idleTime', Session.get('idleTime'));

        if (idleTime > 14) {
            // show modal after 15 minutes
        }
    }
});

Template.example.events({
    'mousemove, mousedown, touchstart, keypress': function() {
        Session.set('idleTime', 0);
    }
});

Solution

I think interval is overkill why not something like this:

var timer;
Template.example.onRendered(function() {
  timer = setTimeout(showModal, 60000* 15);
});

Template.example.events({
    'mousemove, mousedown, touchstart, keypress': function() {
       clearTimeout(timer);
       timer = setTimeout(showModal, 60000* 15);
    }
});
showModal = function(){};

Edit:

You just want to wait for 15 minutes so set a time out for that time and eventually reset timer. Create a timer variable that will hold the timer id so you can reset (delete&recreate) when a user do something.

Leave a Reply

Your email address will not be published. Required fields are marked *