Added delay function and fixed deadlock bug