A little context:
I’ve been trying to get used to reading docs.
I started to make a small fitness app project that will run through an array of set times and show a visual countdown timer.
(Id like to avoid AI help and tutorials for this project)
The code below is not the full project, but shows the current problem I’m trying to solve.
What I want this code to do:
Using a loop:
- set
count
to item in positioni
in the array - run
test()
every second until count reaches zero
(“test” will decrement count every second)
example:
i
should start at position zero of the array
console should show:i = 0
,set count = 3
test()
should then run:
console should show:3
,2
,1
,count = 0
i
should then change to 1
console should show:i = 1
What the code is currently doing:
The loop seems to run through the array first, then run test()
Console shows:
i = 0
, set count: 3
, i = 1
, i = 2
, i = 3
,
3
, 2
, 1
, count = 0
If I do not “set count” in the IF statement, count is set to the last item in the array 7
I’m trying to understand why the loop does not run
test()
between incrementingi
I attempted to use a while loop instead of a for loop, but had the same results.
Code:
(to make it more convenient for people to test, I’ve combine the three files into one HTML doc)
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
body {
margin: 0px;
background-color: green;
}
</style>
</head>
<body>
<script>
let interval;
const arr = [3, 5, 10, 7];
let count = 0;
//Why is this loop increasing value i before makeInt() has a chance to run?
for (let i = 0; i < arr.length; i++) {
console.log("i = ", i);
//count is zero
if (count === 0) {
//The count is set to 3
count = arr[i];
console.log("set count: ", count);
//makeInt() should run the "test" function here, before i is incremented???
makeInt();
}
}
function test() {
if (count !== 0) {
console.log(count);
count--
} else {
console.log("count = ", count);
clearInt();
}
}
function makeInt() {
if (!interval) {
interval = setInterval(test, 1000)
}
}
function clearInt() {
clearInterval(interval);
}
</script>
</body>
</html>