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 of0is 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 usingsetTimeOutwithout 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
cssstylings to make the page looks nicer or you can style to suit your taste.
syntax
- 3. Our search box looks like this adding the
cssstylings.
syntax
Lets add some functionalities
- 4. lets create an
helperfunction that returns an element.
syntax
- 5. Using the above
helperfunction, we can get oursearch-icon,searchBtnelements below:
image
- 6. We add an
eventListenertosearchBtnbuttonsuch that when click we want it to perform some operations:
syntax
syntax
- 7. Defining the
animatefunction, We want the search iconfa-searchto be hidden and spinnerfa-spinnerto animate for 3s when thesearchBtnis clicked. To execute that, we define our animate function below:
syntax
- 8. In passing
searchIconas the third arguments, the setTimeOut method is aware of the icon to restore after thefa-spinnerfinished animating after 3s.
Thanks for reading
Do you wish to get notified when I published a new article? click here











Top comments (0)