Javascript Basics

How to delay in Javascript?

In Javascript, we may face situation where we may want to make the javascript file to wait certain seconds. In simple language, how can we delay a function for certain amount of time.

For this kind of requirement we use setTimeut function.

SetTimeout Function

setTimeout function is used to delay a process for certain amount of seconds.

Syntax

setTimeout(function(){//perform required task},5000);

Example

Lets say, I want to greet user after launching five seconds of the webpage.

<script>

setTimeout(function(){alert(“Good Day Visitor”);},5000);

</script>

 

Upon running above script, the message Good Day Visitor will be alerted to the user after 5 seconds of delay.

Javascript Wait 1 Second

If we want to delay a task only one second, we need to provie 1000 as delay time.

<script>

setTimeout(function(){alert(“Good Day Visitor”);},1000);

</script>