+ 1
setTimeout doesn't work???
This code should output 'hi' once every three seconds up until ten times, but when I run it, they are all output immediately. for (i = 0; i < 10; i++ ) { if (x=1) { console.log ('hi') x=0 setTimeout (x=1, 3000) } else { i-- } }
2 Respostas
+ 3
If you need to use for to iterate the timer setTimeout output, you can use Promise with async/await function to perform it.
function timeout(msg, t) {
return new Promise(resolve => setTimeout(() => resolve(msg), t));
}
async function run() {
for(let i=0; i<10; i++) {
const output = await timeout('hi', 1000);
console.log(output);
}
}
run();
https://code.sololearn.com/W46A9A16a13A/?ref=app
0
@Simba sorry, no that wasn't the problem. This isn't my actual code that I'm working on, but rather a simplified representation of it. That was just a typo