DEV Community

Cover image for Third Argument in JavaScript SetTimeOut Method and Practical Example in Your Next Project
ISIAKA ABDULAHI AKINKUNMI
ISIAKA ABDULAHI AKINKUNMI

Posted on • Updated on

Third Argument in JavaScript SetTimeOut Method and Practical Example in Your Next Project

What is setTimeOut?
SetTimeOut is a global or window method which executes a function taken as an argument once the timer expires.

syntax

timer

Parameters
function can be defined within the method or passed by value to the method.
timer is the delay expected before the function is executed. It's usually in milliseconds. This parameter is optional as a value of 0 is set by default which makes the function executes immediately.

More often in our use of the method, we tend to use only two parameters(function and timer). This article will shed more lights on the use of third arguments and so on.

Example
Let's compare the common way of using setTimeOut without the third argument
syntax

Greetings

Let's see how we can implement the same using third argument

syntax

Third Argument

From the second code, we can see that third and other numbers of arguments is use as argument in the reference function given to the setTimeOut method. In short these arguments are carried forward to the reference function.

Also array can be passed as an argument.

syntax

ArrayOfNumbers

Also an object could be passed as argument. Try that!!

Application in search box
Would you like to animate or spin your search icon pending a request is fulfilled or for some delay. using setTimeOut with third argument will get it done, let's get started

  • 1. we add our form tag, input box and search icons( fontawesome icons).

syntax

HTML

  • 2. We add some css stylings to make the page looks nicer or you can style to suit your taste.

syntax

CSS

  • 3. Our search box looks like this adding the css stylings.

syntax

searchBoxStyling

Lets add some functionalities

  • 4. lets create an helper function that returns an element.

syntax

helperFunction

  • 5. Using the above helper function, we can get our search-icon, searchBtn elements below:

image

searchIcon

  • 6. We add an eventListener to searchBtn button such that when click we want it to perform some operations:

syntax

search Button

syntax

Animate

  • 7. Defining the animate function, We want the search icon fa-search to be hidden and spinner fa-spinner to animate for 3s when the searchBtn is clicked. To execute that, we define our animate function below:

syntax

Animate 2

  • 8. In passing searchIcon as the third arguments, the setTimeOut method is aware of the icon to restore after the fa-spinner finished animating after 3s.

Thanks for reading
Do you wish to get notified when I published a new article? click here

ISIAKA ABDULAHI

Top comments (0)