How do I make a JavaScript function wait before executing (sleep / delay)?

You’ll need to enclose the code that you want to execute after the delay in a function (Func1()). This function will then be called with a delay, in our case from another function (Func1Delay()).

<script type="text/javascript">
function Func1()
{
alert("Delayed 3 seconds");
}
function Func1Delay()
{
setTimeout("Func1()", 3000);
}
</script>

Then you simply call Func1Delay() which in turn calls Func1() but with a delay of 3000 milliseconds (3 seconds):

<body onload="Func1Delay()">
</body>

See this code in action

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top