As per the description and comments, the requirement is the loop should execute infinitely without breaking and should count from 1 -> 20 -> 1.
For this, following code can be used:
function task(profileIndex) {
setTimeout(
() => {
currentPage = profileIndex + 1; // For 0 it would be 1, for 19 it would be 20
// Following line would take care of infinite loop
task((profileIndex + 1) % 20); // % 20 will take care of resetting it to 0 when (profileIndex + 1) is 20. Otherwise, it won't do any manipulation.
},
500 // After every 500ms, the page would be updated.
)
}
task(0)