rewriting
fixing code section using setTimeout per feedback from @richorama.