Search code examples
javascriptjquerycountdown

jQuery continues even if user has left the page


I want to make a page that runs a jQuery script when user gets in the page and the query runs even if user leaves the page or closes the browser. Is this possible?

if(localStorage.getItem("counter")){
  if((localStorage.getItem("counter") >= 300) || (localStorage.getItem("counter") <= 0)){
    var value = 300;
  }else{
    var value = localStorage.getItem("counter");
  }
}else{
  var value = 300;
}
document.getElementById('divCounter').innerHTML = value;

var counter = function (){
  if(value <= 0){
    localStorage.setItem("counter", 0);
    value = 0;
    $( ".exit" ).trigger( "click" );
  }else{
    value = parseInt(value)-1;
    localStorage.setItem("counter", value);
  }
  document.getElementById('divCounter').innerHTML = value;
};

var interval = setInterval(function (){counter();}, 1000);

This is my script. For more detail, this is a countdown from 300 that when user gets in the page it starts and I want to make it like it runs even if user has left the page till it gets 0.


Solution

  • I dare to answer your question and nevertheless hope this will help you. There is no chance to run this js-code after this tab has been closed but you can remember the time an user left your site by setting a time_leave that is set on each interval-round and when an user leaves your site using onbeforeunload:

    var value;
    if (localStorage.getItem('counter')) {
      if ((localStorage.getItem('counter') >= 300) || (localStorage.getItem('counter') <= 0)) {
        value = 300;
      } else {
        value = getElaspedTime();
      }
    } else {
      value = 300;
    }
    
    document.getElementById('divCounter').innerHTML = value;
    
    var counter = function () {
      if (value <= 0) {
        localStorage.setItem('counter', 0);
        value = 0;
        //$('.exit').trigger('click');
      } else {
        value = parseInt(value) - 1;
        localStorage.setItem('counter', value);
      }
      document.getElementById('divCounter').innerHTML = value;
      // set "departure"-time
      localStorage.setItem('time_leave', (new Date()).getTime());
    };
    
    function getElaspedTime() {
      var now = new Date();
      var timeLeft = + localStorage.getItem('time_leave');
      timeLeft = new Date(timeLeft);
      var passedSecs = (now.getTime() - timeLeft.getTime()) / 1000;
      return parseInt(localStorage.getItem('counter')) - parseInt(passedSecs);
    }
    
    window.onbeforeunload = function(){
      // set "departure"-time when user closes the tap
      localStorage.setItem('time_leave', (new Date()).getTime());
    };
    
    var interval = setInterval(function () {
      counter();
    }, 1000);