javascriptjquerysetintervalclearinterval

How to use setInterval and clearInterval as functions


I'm using setInterval with jQuery to change the position of a background-image onLoad but I want to use it as a function so I can call clearInterval to stop it when an element is clicked and to call the function again when another element is clicked but panRight() isn't working on load.

function moveImage() {
var x = 0;
    x-=1;
    $('.bg-img').css('background-position-x', x + 'px');
}

function panRight(){
  setInterval(moveImage(),25);
}

// moveImage onLoad
panRight();

$("#stop-animation").click(function(){
  clearInterval(panRight);
});

$("#start-animation").click(function(){
  panRight();
});

The following code works as intended onLoad and is what I'm trying to refactor as functions.

$(function(){
  var x = 0;
  setInterval(function(){
      x-=1;
      $('.bg-img').css('background-position', x + 'px 0');
  }, 25);
})

Solution

  • You can do it like this:

    function moveImage() {
        var x = 0;
        x -= 1;
        $('.bg-img').css('background-position-x', x + 'px');
    }
    
    var panInterval; // timer id
    
    function panRight() {
      panInterval = setInterval(moveImage, 25);
    }
    
    // moveImage onLoad
    panRight();
    
    $("#stop-animation").click(function() {
      clearInterval(panInterval);
    });
    
    $("#start-animation").click(function() {
      panRight();
    });
    

    Here var panInterval is timer id which get returned whenever we call setInterval and which can be use to clear the interval