replaced thread.sleep with other logic

may possibly cause infinite loop. set a timeout function.