34
loading...
This website collects cookies to deliver better user experience
click
, change
, resize
, scroll
etc. So it's upto the user that how many times they want to run that function. The user can spam any number of times which is not good for the website, because those functions maybe going through heavy computations which may slow the website.setTimeout()
and clearTimeout()
.setTimeout()
function takes a function and a time delay as parameters, call that function after the given delay and returns us a timerId
which we can store. clearTimeout()
function takes that timerId
as a parameter and clears the timeout set by the setTimeout()
function.Throttling is a technique in which no matter how many times user fires the event, the function will run once in a given interval of time.
function
searches the letters typed by the user and returns the data accordingly. By using throttling
here, the function
will be called once in every 1 second.handleChange()
function is called which contains a search()
function.search()
function returns the data according to user typed letters, but it is not yet called.search()
function is passed to throttlingFunc()
as a parameter with delay of 1 second.throttlingFunc()
, it checks if there is some value in timerId
which is a global variable, if true it don't call setTimeout()
.timerId
, it calls the setTimeout()
which calls the search()
and sets previous value of timerId
as undefined.search()
function will be called only after 1 seconds when user types something.Debouncing is a technique in which no matter how many times user fires an event, the function will run only after a certain time after user stops firing events.
debouncing
and the function
will be called after 1 second after user stops typing.handleChange()
function is called which contains a search()
function.search()
function returns the data according to user typed letters, but it is not yet called.search()
function is passed to debouncingFunc()
as a parameter with delay of 1 second.debouncingFunc()
, clearTimeout()
clears the previous timeout by taking previous timerId
value.setTimeout()
which calls search()
and gives new timerId
.search()
function will be called only after 1 seconds when user stops typing something.debouncing
and throttling
technique works while implementing it on a search function.