A different option to those that you have provided in other answers could be using the function requestAnimationFrame of javascript, which allows you to execute (let's say) "recursively" the code you need to execute:
animate();
function animate() {
requestAnimationFrame(animate);
// Aqui iría el código que quieres que se ejecute iteradamente...
}
requestAnimationFrame returns an identifier for each call, which you can use to stop the execution of the code at the time you need it:
var requestID;
animate();
function animate() {
requestID = requestAnimationFrame(animate);
// El código que quieras ejecutar iteradamente iría aquí.
}
$('#stop').click(function() {
cancelAnimationFrame(requestID);
});
The problem with the previous code is that you are not controlling how often the code will be executed. The only thing you would need to do would be to "emulate" the behavior of setTimeout or setInterval.
Here is a functional example of how it would be done:
Note: Here you can find information about the support that requestAnimationFrame has in different browsers.
(function() {
var requestID;
var i = 0;
var last;
var interval = 2000; // Intervalo en milisegundos
animate();
function animate() {
requestID = requestAnimationFrame(animate);
if (canExecuteCode()) {
// El código que quieres ejecutar:
var node = document.createElement('DIV');
node.innerText = ++i;
document.body.appendChild(node);
}
}
function canExecuteCode() {
if (!last) {
last = Date.now();
return true;
}
var now = Date.now();
var elapsed = now - last;
if (elapsed >= interval) {
last = now;
return true;
}
return false;
}
document.getElementById('stop').addEventListener('click', function() {
if (requestID) {
cancelAnimationFrame(requestID);
requestID = undefined;
}
});
document.getElementById('continue').addEventListener('click', function() {
if (!requestID) animate();
});
})();
<body>
<button id="stop">Stop!</button>
<button id="continue">Continue</button>
</body>