Wednesday, June 24, 2009

How to set wait in javascript, JavaScript Delay, JavaScript wait, JavaScript pause



You can use setTimeout() method or false loop to acheive wait functionlity in JavaScript. There is no such wait() or sleep() methods are here in JavaScript.

1. First Example with setTimeout()
Write one Time1.html and paste below code

<html>
CHECK FOR WAIT IN JAVA SCRIPT
<script type="text/javascript" language="javascript1.2">

function waitCheck(){
alert("Binod Kumar Suman");
setTimeout(function(){secondMethod()},2000);
}

function secondMethod(){
alert("Target Corporation");
}

</script>
<br>

<input type="button" value="Check" onClick="waitCheck()"/>
</html>

Just do double click on Time1.html you will get one alert immedialty but only after 2 seconde you will next alert message.

2. Second Example with false loop
Write one Time2.html and paste below code

<html>
CHECK FOR WAIT IN JAVA SCRIPT
<script type="text/javascript" language="javascript1.2">
function waitCheck(){
alert("Binod Kumar Suman");
pauseJS(1500);
secondMethod();
}

function secondMethod(){
alert("Target Corporation");
}

function pauseJS(timeInMilliS) {
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < timeInMilliS);
}

</script>
<br>
<input type="button" value="Check" onClick="waitCheck()"/>
</html>

Just do double click on Time2.html you will get one alert immedialty but only after 2 seconde you will next alert message. :)