What is setTimeOut?
SetTimeOut is a global or window method which executes a function taken as an argument once the timer expires.
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
0is 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.
Let's compare the common way of using
setTimeOutwithout the third argument
Let's see how we can implement the same using 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.
Also an object could be passed as argument.
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(
- 2. We add some
cssstylings to make the page looks nicer or you can style to suit your taste.
- 3. Our search box looks like this adding the
Lets add some functionalities
- 4. lets create an
helperfunction that returns an element.
- 5. Using the above
helperfunction, we can get our
- 6. We add an
buttonsuch that when click we want it to perform some operations:
- 7. Defining the
animatefunction, We want the search icon
fa-searchto be hidden and spinner
fa-spinnerto animate for 3s when the
searchBtnis clicked. To execute that, we define our animate function below:
- 8. In passing
searchIconas the third arguments, the setTimeOut method is aware of the icon to restore after the
fa-spinnerfinished animating after 3s.
Thanks for reading
Do you wish to get notified when I published a new article? click here