Mouseenter and Mouseleave to trigger timer on/off

点点圈 提交于 2019-12-06 15:35:59

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

Just take

clearInterval(timer);

not

clearTimeout(timer);

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/

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

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