Reputation: 365
i have a problem with time. Idk what, but something goes wrong bcz i every single itteration of my function the time is "reducing".
So, i have a function, which changes the label's text. The hole function's duration - 19sec.
(From 0s To 4s) - "Text 1"
(From 4s To 11s) - "Text 2"
(From 11s To 19s) - "Text 3"
Then it repeats. And after a couple of itterations the label changes from "Text 1" to "Text 2" for less than 4s (~3s - ~3.5s)
function TextChanger() {
clearInterval(timer);
timer = setInterval((i => () => {
const parts = { 0: 'Text 1', 4: 'Text 2', 11: 'Text 3' };
if (parts[i]) console.log(parts[i]);
else console.log(i); // 1s, 2s, 3s has passed
i++;
i %= 19;
})(0), 1000);
}
Thanks
Upvotes: 0
Views: 65
Reputation: 1154
I ran the function for a little while in the Chrome Console and got these results consistently:
Text 1
1
2
3
Text 2
5
6
7
8
9
10
Text 3
12
13
14
15
16
17
18
Text 1...
It may be an issue outside your function, an issue specific to your browser, or I don't understand your problem.
I rewrote your code how I would write it, try this format instead:
function TextChanger() {
clearInterval(timer)
var i = 0;
timer = setInterval( () => {
const parts = { 0: 'Text 1', 4: 'Text 2', 11: 'Text 3' };
if (parts[i])
console.log(parts[i]);
else
console.log(i); // 1s, 2s, 3s has passed
i++;
i %= 19;
}, 1000)
}
Upvotes: 1
Reputation: 1435
timers are not reliable since they execute in the main thread with relatively low priority. Set it to run at 900 ms and calculate the time from the last change.
Upvotes: 2