mousemove reset counter jquery

0

With this code, the page redirects to the end of 5 minutes if there is no action, and this happens only in the refresh or when changing the page, but I wanted the counter to reset the mouse and keyboard instead of being 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://pt.stackoverflow.com');
} 

CountDown(300,$('#div'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid="div"></div>
    
asked by anonymous 16.04.2018 / 14:36

1 answer

1

It is simple, you must first set the interVal variable out of the CountDown method, then you simply define the events you want in the document, clear the interVal interval, and call the CountDown method again: / p>

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://pt.stackoverflow.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><divid="div"></div>
    
16.04.2018 / 16:42