0

I want to check if the user is still active on the page by listening to events like click, mousedown, mousemove, keydown, keypress, touchcancel, touchmove, focus, zoom, scroll and more events like this.

I want to check this with an interval of 3 minutes and run a function when the user is still active. The functions needs to be executed once each 3 minutes when there is activity.

If there is no activity then there is no action needed.

Currently what I have:

var app = angular.module('Application_TimeOut', []);

app.run(function($rootScope, $timeout, $document) {    
    console.log('starting run');

    var executeOnceTimeout;

    // Timeout timer value
    var TimeOutTimerValue = 180000;

    // Start a timeout
    var TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
    var bodyElement = angular.element($document);
    
    angular.forEach(['keydown', 'keyup', 'click', 'mousemove', 'DOMMouseScroll', 'mousewheel', 'mousedown', 'touchstart', 'touchmove', 'scroll', 'focus'], 
    function(EventName) {
         bodyElement.bind(EventName, function (e) { TimeOut_Resetter(e) });  
    });

    function LogoutByTimer(){
        console.log('No action needed');
    }

    function TimeOut_Resetter(e){
        console.log(' ' + e);

        if (!executeOnceTimeout) {
            executeOnceTimeout = $timeout(function() {
                console.log('call this function once each time');
                executeOnceTimeout = null;
            }, 2000);
        }

        /// Stop the pending timeout
        $timeout.cancel(TimeOut_Thread);

        /// Reset the timeout
        TimeOut_Thread = $timeout(function(){ LogoutByTimer() } , TimeOutTimerValue);
    }

})

See it on plunker

But this doesn't works as expected, because it keeps looking at the interaction after executing the function, while this should only happen again after 3 minutes. Looks like the timeout doesn't stop.

Tried to change $timeout with $interval but that didn't help.

How can I make it possible that an check on user activity will be runned after 3 minutes and when there is an activity, that the function Timeout_Resettter will be runned once. After that the timer for 3 minutes must be resetted and this must be repeated each 3 minutes and when there is no user activity there is no action needed.

Can
  • 553
  • 1
  • 9
  • 29

1 Answers1

1
  1. Create a service and set current time in the service.
  2. In each activity call the service by passing current time.
  3. Then check in service if the time set is greater than or equals to 3 mins to the earlier time set. If yes then emit an event and handle that event as per your requirement.