hello
i’m trying to make a contdown timer using for loop and setTimeout but the code waits for a second and then run the whole loop all at once even though it’s inside the loop and i don’t understand why it’s doing that.
i tried with and without the immediately invoked function but the result was the same.
here’s my code:
start.onclick = () => {
state.play = !state.play;
const minutes = parseInt(state.counter[0] + state.counter[1])
console.log(minutes)
if (state.play) {
for(let i = minutes ; i > 0 ; i--){
for(let x = 59 ; x > 0 ; x--){
(()=>{
setTimeout(() => {
state.counter = `${state.counter[0]}${state.counter[1]}:${x > 9 ? toString(x)[0] : 0}${toString(x).length == 2 ? toString(x)[1] : x}`
time.innerText = state.counter;
console.log(state.counter)
},1000)
time.innerText = state.counter;
})()
}
(() => {
setTimeout(() => {
state.counter = `${toString(i).length == 2 ? toString(i)[0] : 0 }${toString(i).length == 2 ? toString(i)[1] : i}:${state.counter[3]}${state.counter[4]}`
time.innerText = state.counter;
},6000)
time.innerText = state.counter;
console.log(state.counter)
})()
}
}
}
this is the full code on codepen :
https://codepen.io/3xo13/pen/abYvOQm