Según la descripción y los comentarios, el requisito es que el bucle se ejecute infinitamente sin romperse y cuente desde 1 -> 20 -> 1.
Para esto, se puede usar el siguiente código:
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)