In JavaScript, the code is executed asynchronously. However, there are certain in-built functions in JavaScript which allow us to schedule tasks to be executed after a specific amount of time.
The following are the two functions provided by JavaScript for this purpose:
setTimeout()
methodThe setTimeout()
method executes a particular function after a specific amount of time has elapsed.
Let’s take a look at the syntax of this method:
setTimeout(myFunction, milliseconds, arg(s))
Let’s go over what each of these parameters indicates:
myFunction
: The function to execute.milliseconds
: The time in milliseconds after which the function will be executed. This is an optional parameter. By default, the value is set to 0.arg(s)
: The parameter(s) to pass to the function, if any.The ID of the timer, which is a numeric value, is returned by the function.
Let’s take a look at how we can implement setTimeout()
method:
Clicking on the button will result in the execution of the setAlert()
function, which will display a pop-up on the screen after 4 seconds, only once.
setInterval()
methodThe setInterval()
method repeatedly executes a particular function after a specific amount of time. The function will continue to be executed until specified otherwise.
Let’s take a look at the syntax of this method:
setInterval(myFunction, milliseconds, arg(s))
Let’s go over what each of these parameters indicates:
myFunction
: The function to execute.milliseconds
: The time in milliseconds after which the function will be executed repeatedly. This is not an optional parameter. The minimum value of this parameter is 10.arg(s)
: The parameter(s) to pass to the function if any.
The ID of the timer, which is a numeric value, is returned by the function.
Now that we are familiar with the setInterval()
method, let’s implement it:
The following code will repeatedly display a pop-up on the screen 5 seconds after the button is pressed.