What is setTimeOut?
SetTimeOut is a global or window method which executes a function taken as an argument once the timer expires.
syntax
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 inmilliseconds
. This parameter is optional as a value of0
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 usingsetTimeOut
without the third argument
syntax
Let's see how we can implement the same using third argument
syntax
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
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
- 2. We add some
css
stylings to make the page looks nicer or you can style to suit your taste.
syntax
- 3. Our search box looks like this adding the
css
stylings.
syntax
Lets add some functionalities
- 4. lets create an
helper
function that returns an element.
syntax
- 5. Using the above
helper
function, we can get oursearch-icon
,searchBtn
elements below:
image
- 6. We add an
eventListener
tosearchBtn
button
such that when click we want it to perform some operations:
syntax
syntax
- 7. Defining the
animate
function, We want the search iconfa-search
to be hidden and spinnerfa-spinner
to animate for 3s when thesearchBtn
is clicked. To execute that, we define our animate function below:
syntax
- 8. In passing
searchIcon
as the third arguments, the setTimeOut method is aware of the icon to restore after thefa-spinner
finished animating after 3s.
Thanks for reading
Do you wish to get notified when I published a new article? click here
Top comments (0)