jqueryreloadmouseentermouseleaveidle-timer

Mouseenter and Mouseleave to trigger timer on/off


How would I code a mouseenter event to trigger timer off and a mouseleave event to trigger the timer on?

If the timer interval is reached then webpage will refresh.

I've tried to do it but couldn't work it out:

<script>
    $(document).ready(function() {
        var timer;
        function start() {
            timer = setInterval(function(){refresh()}, 5000);
        }
        start();
        $('body').mouseenter(function() {
            clearTimeout(timer);
        });
    }).mouseleave(function(e) {
        var pageX = e.pageX || e.clientX,
            pageY = e.pageY || e.clientY;

        if (pageX <= 0 || pageY <= 0) {
            start();
        }
        else
            clearTimeout(timer);
    });

    function refresh() {
        window.location.reload(true);
    });
</script>

(This code was partially taken from here: https://stackoverflow.com/a/17714300/2593839)


Solution

  • This code should work :

    function refresh() {
       window.location.reload(true);
    }
    
    var timer;
    function start() {
      timer = setTimeout(function(){refresh()}, 5000);
    }
    
    jQuery(document).ready(function() {
      start();
    
      jQuery('body').mouseenter(function() {
         clearTimeout(timer);
      }).mouseleave(function(e) {
         var pageX = e.pageX || e.clientX,
             pageY = e.pageY || e.clientY;
    
          if(pageX <= 0 || pageY <= 0) {
            start();
          }else {
            clearTimeout(timer);
          }
      });
    });