The Debouncing technique

Event Listeners are really a great bonus for JavaScript. They help in improving the user’s experience and interaction with the web page. JavaScript has a lot of event listeners, a whole lot of them. These event listeners are very active and they keep watching your every move on a webpageย (Beware! They are watching you!). When the desired action/event occurs, they immediately call the function that is attached to them.

As you know, computers are very fast, incredibly fast, a simple event can be fired a zillion times. For example, a scroll event listener will fire a million times for every scroll that you do, the same goes for the resize event. Just imagine how much load it can put on browsers if a function is called million times continuously? Phew! Poor browser ๐Ÿ˜” Here comes our savior and hope “The debouncing and throttling function”.

Debouncing is a technique that is used to limit the rate of execution of a function. This drastically improves the performance of a browser, when a tedious function is attached to an event Listener like onScroll, onResize, etc. A debounce function in minimum takes two parameters – the function to be debounced and the wait time in milliseconds and in turn returns a debounced function. Now with this returned function you can debounce a scroll/resize event handler to be fired once for every specified wait time. A simple debounce function as taken from Underscore.js is given below, it is very simple, it simply calls the function passed to it at regular intervals using the setTimeout and clearTimeout functions.

// From Underscore.js library
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this,
            args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

 

You have read till here and still clueless about what a debouncing function is? I have an analogy for you ๐Ÿ˜ƒ Read until the end!I know a teacher back in my school, she was very good in teaching but at the same time, she had eyes all-over the school, in the walls, canteens, classrooms and literally everywhere. She used to watch all my mischiefs and report them back to my parents immediately. In short, she was a mischief listener (a kind of event Listener). As soon as I do a mischief and before I could reach home, there would be a great welcome ceremony organized by my mom with dad as a chief guest along with spicy scoldings and sometimes with more delightful trashings.

Let me write the above in JavaScript using JQuery

$('Samuel').on('mischief', reportHisParents());
As days went by, I became naughtier and thus she had to often report back to my parents. This was going on until one day, my parents became tired and annoyed by my mischiefs and her reportings. So, one day they visited my school and told her “Hello madam, It is good that you report our sons mistake every now and then, but we are tired of hearing them every day, can you please report them on a monthly basis, during every parents-teachers meet up?”. She replied “I would be glad to”, with an evil smile. From then on, my mischiefs were not reported immediately to my parents but only once in a month, during the Parents-teachers meetup. ๐Ÿ˜ƒ
Then it became
var reportMonthly = debounce(reportHisParents(), 2629800000); 
// 2629800000ms = 1 month

$('Samuel').on('mischief', reportMonthly);

This is what debouncing does, it does not fire a function as soon as it is invoked, instead, it waits for the specified time and then fires the function.

Hope you understood the concept of debouncing. If you like this post and want more posts like this on the web and tech-related topics, please subscribe (there is a button in the bottom right corner). Also feel free to share your thoughts in the comment section ๐Ÿ˜ƒ

Meet you with a next post about throttling function!

PS: I was a very good kid during my school days. You can find me on the first bench, doing all my homework on time and laughing at all the silly jokes that my teachers would crack. The story above was made up just to illustrate the concept of debouncing ๐Ÿ˜ƒ To know more about me visit my blog.

References:
JavaScript Debounceย Function

 

A techie newbie?

Wow! Welcome to the tech field where you have lots of computers, servers, rolling chairs, ACs, etc. It may be a very hard task to transition from college to a job -a software developer. In spite the myths about this job, claiming to be the most paid job, most stressful job, most hair-fall job, most whatever job, it has its own pros and cons. Yet many of the myths are true, the hair-thing for example ๐Ÿ™‚ Just kidding!

When you first step into this field, everything seems a little off and people keep on speaking, attending meetings, tapping the keyboard, etc and you don’t understand what they speak or why ๐Ÿ˜ฆ For two months you will be left alone, I mean you would struggle to make friends and acquaintances. People would stare at you as if you are from Kepler-1229b (an exoplanet) but as days go by, you begin to get along with the people around you. (i.e) You start to code.

When this process begins, you discover new languages, frameworks, and most importantly you will realize that StackOverflow is the greatest treasure you can have. And every time you try to stay cool, some bug would rise up from the code you wrote yesterday and dance before the QA Team. Your bad ๐Ÿ˜ฆ

Even I’m new to this field. I have consolidated few tips that would make you feel better as a fresher in this job -the most paid job ๐Ÿ™‚ Again kidding!!
This post is a bit lengthy, if you want a quick read, just skim through the bold letters.

Mistakes are OK:
Yup! You heard it. No one is perfect. A famous proverb says “Rome was not built in a day”. Perfection comes with practice and experience and they come with mistakes. When you commit a mistake, learn from it and try hard not to repeat it again. One of my favorite quotes -“I never fail, I learn”. Learn from the mistakes of your seniors as well.

Ask questions:
Being new to this field, everything will seem strange and weird. Open your mouth and ask questions if you are not clear about anything. People in the software field are kind. They will surely help you. Do not hesitate to ask a question that has knocked your throat. Just open your mouth and let it out.

Get Help from seniors:
Don’t feel shy to speak with them, they are also fellow human beings with an experience level greater than you. They would always be ready to help you out. Think them as your StackOverflow but do not disturb them often. This might lead them to avoid you, move to another cabin, find another job, etc. Who knows!! Just don’t disturb them with silly questions like “What is 1&&-1 ?”, “Visual Studio is not working, can you help me?”, you could Google it instead ๐Ÿ™‚

Learn/Read/Practice:
I heard people in college say, “All this studying stuff, examinations, semesters will get over within the college, Once into a job, we are free, no exams, no learning, nothing”. My friend, this is not true and you know it. You have to keep on learning as the world moves fast, so does the technological advancement. Frameworks, languages they all mutate every day, make sure that you read a lot and keep your technology stack up-to-date.

Improve writing skills:
Don’t write stories in the comment/work-log. Be straight to the point you wanted to say. Did some changes to the code?? Commit message – “updated bug that was not fixed today”. This type of writing doesn’t help you. In this field, you will have to write a lot of comments, reply to emails, skype with people. Poor writing skills do not help.

Be precise/short and firm in words:
Speak right to the point and use the correct words. Once I was asked by my team lead at the beginning of my career -“What is AJAX ?” I had no idea what it was back then. I knew “A” was for asynchronous so I started with Asynchronous… JQuery… He said “Don’t bluff” ๐Ÿ™‚ All I wanted to make clear is that, if you don’t know something –Don’t bluff ๐Ÿ™‚

Be wise while you code:
Read about OOPS and try to implement them and make the code modular. Use efficient algorithms and do a thorough analysis before you get your hands dirty on the code. Understand why and how the code works and then begin your task.

Keep your passion along with you:
Not everyone has the same passion -coding. Each and everyone may have different hobbies and passion. Do not leave them untamed. Follow your passion. Coding is your profession, passion may be something else. When you feel bored or stressed, ignite your passion and feel the stress relieved.

And finally, Smile always ๐Ÿ™‚
“Face is the index of mind”, radiate joy and confidence to the people whom you meet and talk with. A simple smile can brighten your day.

This is a field where you can develop your logical thinking, programming skills, ability to solve problems, communication skills, comprehending skills, etc. Make use of it. It may be hard in the beginning but as you get involved you will be drawn towards it and stress will stay away from you. For more posts on life skills, visit samuellawrentzz.wordpress.com

Happy coding!!