0

I am using JavaScript and trying to write a function to make the colors blink but the problem is when I click on the toggle blink button it will not stop blinking when I click the stop toggle end button. I am trying to implement clearInterval to make it stop but with no luck. Any help is appreciated.

function main() {
  $('.select-color').on('click', function() {
    var selectedColor = $(this).attr('class');

    switch (selectedColor) {
  case 'select-color cyan not-selected':
    colorClass = 'cyan';
    break;
  case 'select-color yellow not-selected':
    colorClass = 'yellow';
    break;
  case 'select-color magenta not-selected':
    colorClass = 'magenta';
    break;
    }
    $(this).removeClass('not-selected');
    $(this).siblings().addClass('not-selected');
  });

  var colorClass = '';


  $('.box').on('click', function() {
        $(this).toggleClass(colorClass);
    });

  $('.toggle-blink').on('click', function() {
    if (colorClass) {
        $('.toggle-blink').toggleClass('opacity');
    }
    setInterval(function() {
          $('.box.cyan, .box.yellow, .box.magenta').toggleClass('blink');      
                }, 500); 
    });

  $('.toggle-blink-end').on('click', function() {
   scope.clearInterval(main);
  });

}

$(document).ready(main);
Brandon
  • 21
  • 1
  • 2
  • `clearInterval` is used to stop a `setInterval`'s cycling calls to the function that was passed to it – Vivick Aug 18 '17 at 01:00

2 Answers2

2

clearInterval() takes a intervalID as argument, not a function reference, so you would need to store it when calling setInterval() which returns given intervalID:

var intervalID ;

intervalID = setInterval( ... );

clearInterval(intervalID);
0

In order to use clearInterval you need to store the result of setInterval in a variable :

const pid = setInterval(
  /*some func*/,
  /*some duration in ms*/
);

//later on (same scope as pid) 

clearInterval(pid);
Vivick
  • 3,434
  • 2
  • 12
  • 25