If you just want it to animate such that it moves loadingHeight pixels up every 50 milliseconds for a total of 31 loadingHeights, and then repeats back at the starting position, then you can do that in a single animation call, and then repeat that single call, like this:
(function animateImage(steps) {
$(loadingDiv).css('backgroundPosition', '0 0');
$(loadingDiv).animate(
{ backgroundPosition: '0 -' + (loadingHeight * steps) + 'px' },
{ duration: 50 * steps, complete: function() { animateImage(steps); } }
);
})(31);
The general way to do an infinite or indefinite loop in javascript is to define a function that calls itself immediately and then periodically, like this:
(function someName() {
// do some stuff
// then after some delay (setTimeout or animate delay, etc...), call:
someName();
})();