Javascript Loop Wait For Function To Finish