Debounce And Throttle in Javascript

The greatest concern faced by UI developers is the performance issues in situations where functions are being executed excessively and in some cases unnecessarily


There are two ways in order to control the execution of functions using Debounce and Throttle, which come in handy when on handling events such as mouse scroll or window resizing.

A simple explanation of debounce and throttle is that the number of times a function is executed over a period of time is throttle and the time passed between each execution of a function is implemented as debounce.

 

Real Time Example:

Debounce: The perfect example for debounce would be resizing of the window in a desktop. Imagine we are to get the value of the screen size, but it would be useless to execute the function as the user drags on the size of the screen but we would be interested only in the final value of the screen size after it has been resized, as explained in the link(https://css-tricks.com/debouncing-throttling-explained-examples/)

debounce

Throttle: An example of throttle can be explained through the infinite scroll, where we have to determine the scroll position and load data before the user reaches the bottom. In this case, it wouldn’t be advisable to use debounce, as it would allow us to call the function only after the user stops scrolling. But throttle would ensure that we constantly check how far is the user from the bottom and act accordingly.

throttle

The major advantage of throttle over debounce is that we have the option to store ignored executions and execute them at last after all the function calls are made

Implementation:

A code sample for implementation of debounce

//original code from  Jhey Tompkins blog

//https://medium.com/@_jh3y/throttling-and-debouncing-in-javascript-b01cad5c8edf

var debounce = function(func, delay) {

var inDebounce = undefined;

return function() {

  var context = this,

    args = arguments;

  clearTimeout(inDebounce);

  return inDebounce = setTimeout(function() {

    return func.apply(context, args);

  }, delay);

}

}

 

The above function could be linked to a click event as follows:

 

debounceBtn.addEventListener(‘click’, debounce(function() {

return console.log(‘Hey! It is’, new Date().toUTCString());

}, 3000));

 

In the above code, when the button click event is called the function gets executed with the delay of 3 seconds, but if another click event is triggered before the execution of first click, then it is replaced by the second event.

 

Similarly, a code implementation for throttle would be

 

//original code from comment of maninak

//https://gist.github.com/makenova/7885923

function throttle(func, msWait) {

var time = Date.now();

return function() {

if ((time + (msWait || 100) – Date.now()) < 0) {

func();

time = Date.now();

}

}

}

Can be used as:

window.addEventListener(‘scroll’, throttle(myOnScrollFunction), false);

The above code ignores execution of the function for the events that are being called within 100ms of execution of the previous function call.

Conclusion:

Debounce and Throttle are techniques used to optimize the event handling.Both throttling and debouncing will rate-limit execution of a function.

In Summary:
Debounce will bunch a series of sequential calls to a function into a single call to that function. It ensures that one notification is made for an event that fires multiple times.

Throttle will delay executing a function. It will reduce the notifications of an event that fires multiple times.

References:
1.https://css-tricks.com/debouncing-throttling-explained-examples/
2.https://medium.com/@_jh3y/throttling-and-debouncing-in-javascript-b01cad5c8edf
3.https://gist.github.com/makenova/7885923

4.https://stackoverflow.com/questions/25991367/difference-between-throttling-and-debouncing-a-function

5.http://reactivex.io/documentation/operators/debounce.html#collapseRxNET

6.http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-throttleTime

 

Tips to Avoid Stage Fear

     Stage Fear is a common issue that every one of us face at some point in life. It could be during when we do a session or seminar or even when we have a job interview.

    We all talk in our day to day life to another person or a group of people.Then why do we get stage fear when we do a presentation? The answer is because in our daily lives we are being ourselves, we are not self conscious on what we talk with a friend/family. So why let other people bother us? We could suppress our stage fear with few changes to our mind set. I hope the following factors changes yours.

  1. Love your work
  2. Have confidence on yourself
  3. Start with a joke
  4. Acceptance of the worst
  5. Know what you are doing
  6. Just 5 minutes
  7. Be Punctual
  8. Take care of yourself
  9. Use your Imagination

And Last but not the least

  1. Don’t forget to breathe 😛

Love your work

      This is the most important part of avoiding your stage fear. Remember the time you were talking about a movie you just watched and loved or your favourite book? You would be feeling so overwhelmed with passion, that you forget about everything around you. If you could bring out this passion during your presentation. Then voila!!!! you’ll be surprised on how you pulled off a magical perfect speech.

Have confidence in yourself

      Hmmm confidence…. the thing we lack most during a speech, which makes us screw  our presentation. The best way to tackle this is by, encouraging yourself. And hey who can judge you better than yourself !! So boost up your confidence level and say ‘All is well’ 😉

Start with a joke

      People forget the important aspect of life when they are stressed out, LAUGHTER.

laugh

      So throw in a joke when you start a presentation. It would ease your fear and the mood of the audience . And you are up with a kick start to the presentation.

Acceptance of the worst

      Did you know that there is no such thing as a ‘Perfect Presentation’? Weird right? So why do we have to worry over it? Have a prior mindset that there are possibilities of mistakes. Even if you make mistakes, who cares? There’s always a next time. But be bold to accept your mistakes.

Know what you are doing

prepare

      Choose a topic which you are comfortable with, for the presentation. Prepare the content  beforehand( It’s not necessary to be as perfect as ‘Hermoine’ :P, but at least be ‘Harry’ and not ‘Ron’ 😉 , forgive my ‘Harry Potter’ reference ) . Knowing that you have done all your best to prepare will make your nerve calm down a bit.

Just 5 minutes

      Studies show that, the stage fear is at the peak during the first five minutes of the presentation. If you did a good job during this 5 minutes, then nothing can stop you from giving you best presentation ever.  You could go through this 5 minutes by interacting with the audience or starting off with a funny story. But don’t forget that you should never be critical of the audience.

Be Punctual

      Be at the venue at least 15 mins before the presentation, so that you could avoid last minute traffic or you could also socialise with the audience before the speech, you would make some friends and talking with friends never freaks us out right?

Take care of yourself

      Concentrate on keeping yourself fit for the presentation. A healthy body boosts up your confidence rate through the roof. Most importantly, eat a Banana.

banana

      Yeah, you heard me right!. Eat a banana before your presentation. Because eating something nutritious and not too filling will help with the butterflies in your stomach.

Use your imagination

      Remember the person who sat beside you in your kinder garden. The person sitting in the last row could be them or it couldn’t? But hey, if it helps you that someone you know is listening to you, won’t you feel better? So run wild with your imagination,it will help you reduce your fear.

Don’t forget to breathe

Yeah I know it’s silly

              .meditation

      But people when stressed, do forget to breathe. They just want to get the presentation to be over with as soon as possible and so they start reciting the summary they prepared with a fast pace. They think it will help with the stage fear. But actually it makes them worse. Taking deep, long breaths and going slow on the presentation is a much better way of avoiding the stage fear.

 

“The brave man is not he who does not feel afraid, but he who conquers that fear.”

                                                                                                                                   –Nelson Mandela

So as Mandela says, ‘Lets go conquer the fear ‘