/* initial variable declarations */
var el = document.getElementsByTagName('div')[0];
var btn = document.getElementById('stop');
var i = 0,
currPos = 0,
pauseInterval, runningInterval,
running = true,
bgSize = parseInt(window.getComputedStyle(el).backgroundSize.split('px')[0], 10);
/* toggle button listener */
btn.addEventListener('click', function() {
running = !running; // toggle state
if (!running) {
i = 0;
currPos = parseInt(el.style.backgroundPositionX.replace('px', ''), 10);
clearInterval(runningInterval); /* stop the normal animation's timer */
pauseInterval = setInterval(function() {
slowPause(currPos); /* call the slow pause function */
}, 10);
} else {
i = 0;
currPos = parseInt(el.style.backgroundPositionX.replace('px', ''), 10);
clearInterval(pauseInterval); /* for safer side, stop pause animation's timer */
runningInterval = setInterval(function() {
anim(currPos); /* call the normal animation's function */
}, 10);
}
});
/* slowly pause when toggle is clicked */
function slowPause(currPosX) {
el.style.backgroundPosition = (currPosX + (i * .025)) % bgSize + 'px 0%';
i += 10;
if (i >= 1000) { /* end animation after sometime */
clearInterval(pauseInterval);
i = 0;
}
}
/* increment bg position at every interval */
function anim(currPosX) {
el.style.backgroundPosition = (currPosX + (i * .25)) % bgSize + 'px 0%';
i += 10;
}
/* start animation on load */
runningInterval = setInterval(function() {
anim(currPos);
}, 10);
.animated-bg-pos {
height: 100px;
width: 200px;
background-image: linear-gradient(to right, red 25%, blue 25%, blue 50%, orange 50%, orange 75%, green 75%);
background-size: 800px 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/prefixfree/1.0.7/prefixfree.min.js"></script>
<div class='animated-bg-pos'></div>
<button id='stop'>Toggle Animation State</button>