Is there a way to run this loop once and pass the time as a parameter? There is a lot of repeat code here.