var i=0;
function counter(){
for( i;i<100;i++){
setTimeout(()=>{
console.log(i);
},2000)
}
}
counter();
i wa
Use setInterval(), like this:
var i=0;
var intervalID;
function printAndIncrement()
{
// Stop interval procedure when "var i" reach to 100.
if (i > 100)
{
clearInterval(intervalID);
return;
}
console.log(i);
i++;
}
intervalID = setInterval(printAndIncrement, 1000);
How can i print in interval of 2 second?
'Drift' due to CPU time is a consideration.
If your use case is running code spaced 2 seconds apart minimum, use setTimeout()
:
let ctr = 1
const fn = () => {
console.log(ctr++)
setTimeout(fn, 2000) // set the next run
}
setTimeout(fn, 2000) // set 1st run
If your use case is running code spaced 2 seconds apart maximum, use setInterval()
:
let ctr = 1
const fn = () => console.log(ctr++)
setInterval(fn, 2000)
More on JS CPU Timer drift here: https://johnresig.com/blog/how-javascript-timers-work/
Cheers,
function counter(){
for( let i=0;i<100;i++){
setTimeout(()=>{
console.log(i);
},2000)
}
}counter();
Just change var
to let
const printNumbersForEvery2Sec = (n) => {
for (let i = 1; i <= n; i++) {
setTimeout(() => {
console.log(i)
}, i * 2000)
}
}
printNumbersForEvery2Sec(10);
Taken from here