More refactorings, added a threadSleep function