Reza Saadati
Reza Saadati

Reputation: 1274

clearInterval() not working and returns no errors

I would like to run a function, when a checkbox is checked and stop that function, when the checkbox is not checked.

This is how I tried it:

$('#auto').on('click', function() {
    if ($(this).is(':checked')) {
        // Interval
        var autoInterval = window.setInterval(function() {
            navi('next');
        }, 1500);
    }
    else {
        clearInterval(autoInterval);
    }
});

The problem is clearInterval() does not work and I get no errors.

https://jsfiddle.net/n339tzff/9/

It will work if my code looks like this:

// Interval
var autoInterval = window.setInterval(function() {
    navi('next');
}, 1500);

// Auto Play
$('#auto').on('click', function() {
    if ($(this).is(':checked')) {
        autoInterval;
    }
    else {
        clearInterval(autoInterval);
    }
});

But then I have another problem... I only want to run the function navi('next') when I click on the checkbox and not at the beginning.

Upvotes: 3

Views: 228

Answers (2)

Suren Srapyan
Suren Srapyan

Reputation: 68655

When you click, it calls the setInterval and stores the result of the call in the autoInterval and after ending the function removes it. So you store and lost the value of your variable every time in the same call.

Declare the autoInterval variable outside of the event handler, to make it independent from the event handler's scope. Also you can wrap your function with a IIFE to not mutate this variable outside

(function() { 

   var autoInterval;

   $('#auto').on('click', function() {
      if ($(this).is(':checked')) {
         autoInterval = window.setInterval(function() {
           navi('next');
         }, 1500);
      } else {
         clearInterval(autoInterval);
      }
   });

})();

Upvotes: 6

Jono20201
Jono20201

Reputation: 3205

You should define autoInterval outside of the event handler function, as after the event has run this variable would be 'discarded'/un-accessable.

var autoInterval = null;

$('#auto').on('click', function () {
    if ($(this).is(':checked')) {
        autoInterval = window.setInterval(function () {
            navi('next');
        }, 1500);
    }
    else if(autoInterval !== null) {
        clearInterval(autoInterval);
        autoInterval = null;
    }
});

Upvotes: 2

Related Questions