1

I am trying to repeat an interval on document ready. Interval repeats every 3 seconds but I want it halt it onmousemove event for 5 seconds and then restart interval.

This is my code as far:

$(document).ready(function(){
    var myInterval = setInterval(alertMe, 3000);

    function alertMe(){
        alert('jj');
    }

    $(document).mousemove(function(event){
        // I want delay 5 seconds and then initialize myInterval again
        setTimeout(function(){}, 5000);
        clearInterval(myInterval);
        setInterval(alertMe, 3000);
    });
});

Reference Answer 1: JavaScript: How to get setInterval() to start now?

Reference Answer 2: How to wait 5 seconds with jQuery?

Danial212k
  • 130
  • 1
  • 10

2 Answers2

0

you can try below code which is little modification to your code only. You can use mousedown event handler and inside it clearinterval and set new interval after 5 seconds using settimeout

$(document).ready(function(){
    var myInterval = setInterval(alertMe, 3000);
    var myTimeout;

    function alertMe(){
        alert('jj');
    }

    $(document).mousedown(function(event){
        clearInterval(myInterval); // clear interval as soon as mouse over
        clearTimeout(myTimeout);
        // I want delay 5 seconds and then initialize myInterval again
        myTimeout = setTimeout(function(){
           myInterval = setInterval(alertMe, 3000); // set interval after 5 seconds
        }, 5000);
    });
});
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
  • You'll also need to clear the timeout, otherwise the interval will restart even if the mouse moves again before the delay finishes. – Rory McCrossan Sep 19 '19 at 09:22
0

Firstly note that your question says you want to stop the interval on mousedown, yet your code uses mousemove.

Secondly, don't use alert() to test this as it blocks the UI from updating. Use console.log() instead.

Finally, to solve the issue, use a setTimeout() call in the mouse event to delay the restarting of the interval. Try this:

$(document).ready(function() {
  function logMe() {
    console.log('jj');
  }
  
  function startInterval() {
    return setInterval(logMe, 3000);
  }
  
  var interval = startInterval(), timeout;

  $(document).mousemove(function(event) {
    clearInterval(interval);
    clearTimeout(timeout);
    
    timeout = setTimeout(function() {
      interval = startInterval();
    }, 2000); // note 2000 delay here, as it compounds with the 3000 delay on the 
              // interval to make a 5000ms delay
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339