Why do I have double values? I am using useEffect and the setInterval function. In the setInterval function there is a single increment or decrement and after a second there is another one. Why am I getting a double value in the results? How to change it?
const demo = "1 2 3 4 5";
let i = 0;
let j = demo.length;
useEffect(() => {
const interval = setInterval(() => {
if (i < demo.length) {
console.log(demo.substring(0, i));
i++;
} else if (j > 0) {
console.log(demo.substring(0, j));
j--;
}
}, 1000);
}, [i, j]);
Result:
1
1
1 2
1 2
1 2 3
1 2 3
1 2 3 4
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3 4
1 2 3
1 2 3
1 2
1 2
1
1
You are not getting double values, you are getting the spaces in the demo string.
You results is
'1'
'1 '
'1 2'
'1 2 '
'1 2 3'
'1 2 3 '
'1 2 3 4'
'1 2 3 4 '
'1 2 3 4 5'
'1 2 3 4 '
'1 2 3 4'
'1 2 3 '
'1 2 3'
'1 2 '
'1 2'
'1 '
'1'