+ 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-- } }

8th Jul 2021, 1:21 PM
Blake Grass
Blake Grass - avatar
2 Réponses
+ 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
8th Jul 2021, 1:55 PM
Calviղ
Calviղ - avatar
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
8th Jul 2021, 2:08 PM
Blake Grass
Blake Grass - avatar