Another possibility is, taking example from here, the usage of Web Workers:
let mySetInterval = function(callback, timeout) {
let blob = new Blob([ "self.addEventListener('message', function(e) { \
let old_date = Date.now(); \
while (Date.now() - old_date <= " + timeout + ") {}; \
self.postMessage(true); \
}, false);" ], { type: "text/javascript" });
let worker = new Worker(window.URL.createObjectURL(blob));
worker.addEventListener("message", function(e) {
if (callback() === false) {
return
}
mySetInterval(callback, timeout)
}, false);
worker.postMessage(true);
};
var a = 0;
mySetInterval(() => { if (a >= 10) { return false } else { console.log(a++) } }, 1000)
console.log(45);
Every 1 second it updates the variable a
with +1.
Like you see, in this way it is non-blocking and it will stop when the variable a
is 10.
To clear the "interval", in this case simply return false
inside the callback. Obviously is not the same as the clearInterval
function! Here there is not something like an ID such as for the setInterval
function.