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

 

What really is Javascript’s Event Loop

All of us know Javascript is a “single-threaded non-blocking asynchronous concurrent language, It has a call stack, an event loop, a callback queue, some other apis and stuffs” . We have also heard about V8 – Chrome’s Javascript runtime engine.

Many of us have known already about Javascript’s Event loop, but for the newbies this must be a good read.

Putting the big picture,

Squashapps-chrome-runtime

Let’s see what happens when this piece of code is executed,


console.log('hi');
setTimeout(function cb() {
console.log('JSC');
},5000);
console.log('how are you');

The result in the console would be,
hi
how are you
JSC

How this code is manipulated in V8 is,

  • When that piece of code is executed, console.log(‘hi’) is pushed onto the stack and “hi” is printed in the console.

Eventloop

  • The next thing is, the timeout function is triggered. The timeout function is not in the stack so a timer is kicked off in the webapis  which will run for 5 secs.

Eventloop-timeout

  • Since the timer is run by the webapi and also the stack is empty, console.log(‘JSC’) is pushed onto the stack and “JSC” is printed in the console.

Eventloop-2

  • After 5 sec, once the timer is done the function is queued up in the task queue

Event loop

  • Here is where the event loop comes into picture, the job of the event loop is to execute the task queue in a FIFO manner only when the stack is empty.

So, you may have a question “What if some process is taking place in the stack and the timeout is done?”  The answer is the timeout function will be put onto the queue and it will wait until the stack is empty, no matter how many seconds timeout you gave.

What do you think will be the output for this code?


for(var i=0; i<1000000000; i++) {
console.log(i);
if(i===0){
setTimeout(function cd() {
console.log('hi');
},2000);
}
}

I was asked the same question by my CEO one day in my office, the next moment i replied
0,1,2,3 and so on and after 2 secs some where in between
‘hi’ and then all the way to
…. 1000000000

But that’s not right, I totally forgot about the event loop. The exact output would be
0,1,2,3, … ….. …… , 1000000000
hi

You may ask me, what if I give a timeout(function(), 0); , even then the timeout function is going to go to the task queue and it should wait until the event loop is triggered and will be triggered  when the stack is empty 😉

“Go through this wonderful presentation by Philip Roberts which was my inspiration”.

Beware of the Event loop!

Happy coding!

How to implement SwiperJs slides with IONIC 1.x using ion-slides

With the release of V1.2, ionic announced the support for SwiperJs with the new directive ion-slides. The older ion-slidebox will be deprecated over the new ion-slides. As there was very less documentation and a lot of developers confused on how to get an instance of the swiper in your controller, I decided to write this blog post.

Here’s the forum where I posted the original answer

AngularJS Controller

 

How to use ion-slides in IONIC
AngularJS Controller


HTML

Screen Shot 2016-07-05 at 11.38.31 AM
HTML part

REFERENCES

  1. It can be made much more extensible. The different options available for
    the swiper like effect, speed ..etc is here (Look under Swiper parameters)
  2. Take a look at the api docs here
  3. Awesome Swiper Demos here
  4. Here’s an example gist

With IONIC 1.2 release’s support of swiper, the mobile hybrid developers could now unleash the power of SwiperJS!

Happy coding!