user1615837
user1615837

Reputation: 89

How can I stop a repeating function when the mouse is clicked?

I could really use some help. I have a javascript / jquery slider below that repeats over and over. I would like it to stop repeating when a specific button is clicked if possible. I am a complete novice and it took a lot to get to this point! Any help would be greatly appreciated.

$(document).ready(function () {

    var i = 0;
    var z = 0;
    delay = 5000;
    var el = $('#scroll-script');
    var ql = $('#info-box');
    var classesb = ['fp-info-one', 'fp-info-two', 'fp-info-three', 'fp-info-four'];
    var classes = ['fp-slide-one', 'fp-slide-two', 'fp-slide-three', 'fp-slide-four'];
    var interval = setInterval(function () {
        el.removeClass().addClass(classes[i]);
        i = (i + 1) % 4;
        ql.removeClass().addClass(classesb[z]);
        z = (z + 1) % 4;
    }, delay);

});

Upvotes: 0

Views: 1955

Answers (4)

Jonas
Jonas

Reputation: 71

You just need to use clearInterval():

$(".somebutton").click(function()
{
  clearInteval(interval);
  interval=null;
});

Upvotes: 1

gabitzish
gabitzish

Reputation: 9691

Use clearInterval(interval) when you want to stop the repeating action.

something like :

 $('#btn').on('click', function(){ clearInterval(interval); });

Upvotes: 0

thecodeparadox
thecodeparadox

Reputation: 87073

$(document).ready(function () {

    var i = 0;
    var z = 0;
    delay = 5000;
    var el = $('#scroll-script');
    var ql = $('#info-box');
    var classesb = ['fp-info-one', 'fp-info-two', 'fp-info-three', 'fp-info-four'];
    var classes = ['fp-slide-one', 'fp-slide-two', 'fp-slide-three', 'fp-slide-four'];
    var interval = setInterval(function () {
        el.removeClass().addClass(classes[i]);
        i = (i + 1) % 4;
        ql.removeClass().addClass(classesb[z]);
        z = (z + 1) % 4;
    }, delay);

    // code that stop repeat
    $('#your_button').on('click', function() {
      clearInterval(interval );
    });
});

As, you're using setInterval() for repeating time, so to clear that timer you need to use clearInterval()..

Note

#your_button will be replace with appropriate selector for your target button.

Upvotes: 2

jogesh_pi
jogesh_pi

Reputation: 9782

i think clearInterval() help you to achieve this.

just apply this on click() event. something like:

$('#element').click(function(){
    clearInterval(Interval_OBJECT);
});

Upvotes: 0

Related Questions