Mouseenter and Mouseleave to trigger timer on/off

此生再无相见时 提交于 2019-12-23 04:04:37

问题


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)


回答1:


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);
      }
  });
});



回答2:


Just take

clearInterval(timer);

not

clearTimeout(timer);



回答3:


You can do something like that:

var mytimeout;
$('.box').on('mouseenter', function() {
  if(mytimeout) {
    clearTimeout(mytimeout);
  }

}).on('mouseleave', function() {
  mytimeout = setInterval(function() {
    console.log('tick');
  },1000);    
});

See fiddle: http://jsfiddle.net/uXrKG/




回答4:


This should work for you.

var mytimeout, i;
i = $('.box').text();

$('.box').on('mouseenter', function() {
    if(mytimeout) {

        clearInterval(mytimeout);
    }

}).on('mouseleave', function() {
    mytimeout = setInterval(function() {
        $('.box').text(i++);
    },1000);    
});

DEMO

Should use clearInterval not clearTimeout



来源:https://stackoverflow.com/questions/17716848/mouseenter-and-mouseleave-to-trigger-timer-on-off

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!