-1

I have a timer inside document.ready. Like this:

$( document ).ready(function() {

    timer = window.setInterval(myAction, 3000);

});

Then I have a function called pauseTimer() like this:

function pauseTimer() {

   timer.pause();           

}

But.. why this is not working?

Russel Riehle
  • 267
  • 1
  • 11

2 Answers2

0

You can not pause an interval. You can only stop/clear the interval and restart it again if needed.

var timer;

function myAction() {
  console.log('my action');
};

$( function() {
  
  $(document).on('click', '#start', function(){
    timer = window.setInterval( myAction, 3000 );
  });
  
  $(document).on('click', '#stop', function(){
    window.clearInterval( timer );
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="start">Start/Restart interval</button>
<button id="stop">Stop interval</button>
Flyer53
  • 754
  • 6
  • 14
0

You can try this

$( document ).ready(function() {
   var timer = window.setInterval(myAction, 1000);
   function pauseTimer() {
    clearInterval(timer )          
   }
   function playTimer() {
    timer = window.setInterval(myAction, 1000);         
   }
   function myAction(){
   console.info('myAction')
   }
   $("#play").click(function(){
     playTimer()
   });
   $("#pause").click(function(){
     pauseTimer()
   });
});

HTML

<div>
  <button id="play" >play</button>
  <button id="pause"  >pause</button>
</div>
Manoj Lodhi
  • 978
  • 4
  • 10