Search code examples
jquerydelaysetintervalclearinterval

How to restart interval after a short delay jquery


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?


Solution

  • 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>