replaced while loop with setTimeout