I'm a JavaScript newbie and I'm trying to achieve concurrent actions with setInterval
and setTimeout
.
What I'd like to achieve, what actually happens and what I expected to happen is best explained with the following code.
var myVar = setInterval(function() {
myTimer()
}, 1000);
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
for (var i = 0; i < 100; i++) {
setTimeout(function() {
console.log("log " + i);
}, 3000);
}
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
My expectation for the leading setInterval
, is that the function myTimer
is executed every second, independent of what happens afterwards. Except of course if the site is closed or clearTimeout
is called on the myVar
.
I can not verify if this action really happens independently and in an ongoing manner.
The following for loop, is there to simulate further code, to see if the myTimer
function would be executed independently.
I expected the loop to start with i=0
, then wait for three seconds, log log 0
to the console, then continue with i=1
and so on.
Instead it appears that the timeout is started and in the meantime i
has reached the end of the for loop and is therefore 100
.
How do I get the for loop to wait with the iteration for the setTimeout
?
And is the setInterval
really executed every second, independent of the following code? E.g. if the following code had actions that take some processing/time, would the clock update anyways, during the processing?