Mousemove reset counter jquery

Asked

Viewed 28 times

0

With this code, the page redirects after 5 minutes if there is no action, and this only happens in refresh or when changing pages, but, intended that the counter reset the movement of the mouse and keyboard instead of in the action of the page itself.

function CountDown(duration, display) {
	if (!isNaN(duration)) {
		var timer = duration, minutes, seconds; 
		var interVal=  setInterval(function () { 
			minutes = parseInt(timer / 60, 10); 
			seconds = parseInt(timer % 60, 10); 
			minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; 

			$(display).html("<b>" + minutes + "m : " + seconds + "s" + "</b>"); 
			if (--timer <= 0) {
				timer = duration; 
				SubmitFunction(); 
				$('#div').empty(); 
				clearInterval(interVal) 
			} 
		},1000);				
	} 
} 

function SubmitFunction(){ 
	$(location).attr('href', 'https://answall.com');
} 

CountDown(300,$('#div'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div"></div>

1 answer

1


It’s simple, first you must set the variable interVal out of method CountDown, then just set in the document the events you want, clear the range of interVal and recall the method CountDown:

var interVal;
function CountDown(duration, display) {
  if (!isNaN(duration)) {
    var timer = duration, minutes, seconds;
    interVal = setInterval(function () {
...

$(document).on('mousemove click keyup', function(e) {
  clearInterval(interVal);
  CountDown(300, $('#div'));
});

See working:

var interVal;
function CountDown(duration, display) {
  if (!isNaN(duration)) {
    var timer = duration, minutes, seconds;
    interVal = setInterval(function () {
      minutes = parseInt(timer / 60, 10);
      seconds = parseInt(timer % 60, 10);
      minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds;

      $(display).html("<b>" + minutes + "m : " + seconds + "s" + "</b>");
      if (--timer <= 0) {
        timer = duration;
        SubmitFunction();
        $('#div').empty();
        clearInterval(interVal)
      }
    }, 1000);
  }
}

function SubmitFunction() {
  $(location).attr('href', 'https://answall.com');
}

CountDown(300, $('#div'));

$(document).on('mousemove click keyup', function (e) {
  clearInterval(interVal);
  CountDown(300, $('#div'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div"></div>

  • not only the answer but also the explanation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.