Always wondered that why does Javascript do not have some extraordinary functions like trim, wait, sleep etc. Oh well, i think at that time they din bother to add them or din feel the requirement.
I was working on a script last week and somehow i wondered if i can trick around such that my JavaScript wait for few seconds and after that runs the awesome code. There are two ways of doing that, as follows
The customized Sleep way :
<script type="text/javascript">// <![CDATA[ function sleep(ms) { var dt = new Date(); dt.setTime(dt.getTime() + ms); while (new Date().getTime() < dt.getTime()); } // ]]></script><script>// <![CDATA[ sleep(4000); alert("we are done"); // ]]></script> |
Using Javascript’s setTimeout func :
setTimeout("alert ('called from setTimeout()');",4000); |
Difference between setTimeout and sleep()
The difference between the above function is that sleep will halt the script and will not allow the script to execute further lines of code. However when setTimeout is called, it won’t halt the further execution of the script, instead it will execute after the specified interval of time and also the other functions (if any) will keep on executing.
if you want to check this scenario .. just copy paste the below code into the body section and comment, sleep and setTimeout function calls one by one to notice the difference.
<script>// <![CDATA[ //sleep(4000); setTimeout("alert ('called from setTimeout()');",4000); alert("we are done"); // ]]></script> |
Hope this helps.
Cheers !!
Sachin Khosla