March 24, 2012

jQuery play/pause jQuery function

Question by Yusaf

What I’m trying to do is play and pause a function ie press a button to start a fucntion press a button to pause so on. I am not entirely sure how this can be done i have tried .live() and .die() but they don’t work.

Fiddle

I have the HTML below

<button class="play">play</button>
<button class="pause">pause</button>
<div class="divafter"></div>​

and the jQuery which I’m not entirely sure what .die() does but on the jsfiddle seems to speed up the interval time.

(function($){
  playing = function() {
window.setInterval(function() {
    $(".divafter").after("playing <br/>");
}, 500);
};
})(jQuery);
$(".play").click(function(){
    playing().live();
});
$(".pause").click(function(){
    playing().die();
});​

Answer by j08691

Try this jsFiddle example. You need to use clearInterval() to stop setInterval().

jQuery:

var foo;
playing = function() {
    foo = window.setInterval(function() {
        $(".divafter").after("playing <br/>");
    }, 500);
}

$(".play").click(function() {
    playing();
});
$(".pause").click(function() {
    clearInterval(foo);
});​

Answer by Starx

You will have to the clearInterval to simulate the pause effect.

Grab the instance of the interval like this

playing = setInterval(function() {
            $(".divafter").after("playing <br/>");
          }, 500);

And clear to pause

clearInterval(playing);

Usage on your code would be this:

var playstatus;
(function($){
    playing = function() {
        return setInterval(function() {
           $(".divafter").after("playing <br/>");
           }, 500);
    };

})(jQuery);

$(".play").click(function(){
    playstatus = playing();
});
$(".pause").click(function(){
   clearInterval(playstatus);
});

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!