var i=0;
function counter(){
for( i;i<100;i++){
setTimeout(()=>{
console.log(i);
},2000)
}
}
counter();
i wa
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,