Tutorial Membatasi Pemanggilan Event dengan jQuery Debounce & Throttle

Category : Tutorial - 04 September 2017 20:56:30
Tutorial Membatasi Pemanggilan Event dengan jQuery Debounce & Throttle

jQuery merupakan javascript library yang sangat terkenal dengan fasilitasnya yang cukup lengkap. Fitur-fitur jQuery yang dapat digunakan misalnya seperti seleksi Document Object Model (DOM), AJAX, Efek animasi, dan juga Event Listener. Di post kali ini kita akan lebih fokus ke fitur Event Listener di jQuery.

Fitur event yang disediakan jQuery cukup banyak, misalnya event click, dblclick, scroll, change, focus, hover, keydown, keypress, keyup, resize, dan masih banyak lagi. Ketika kita ingin menggunakan event tersebut, jQuery akan melakukan proses pengecekan pergerakan event tersebut setiap saat. Yang jadi masalahnya adalah, jQuery mengecek event tersebut setiap 1 milidetik (0,0001 detik), dan apabila kode yang kita gunakan kurang efisien, maka hal tsb bisa bikin browser client jadi hang. Contoh ilustrasinya seperti ini : 


$("object").on("mousemove", function(){
    //baris block function ini akan selalu dieksekusi
    //setiap milidetiknya apabila mouse masih bergerak
    //didalam objek ini.
    //bisa dibayangkan, kalau function ini berisi perintah rumit
    //artinya setiap milidetiknya akan dijalankan terus-menerus
    //dan bisa membuat browser lemot & hang
});

Contoh kode diatas kesannya memang normal, akan tetapi seluruh kode yang ada didalam function event tersebut akan selalu dieksekusi per milidetiknya apabila ada perubahan sesedikit apapun. Untuk mengatasi hal tersebut, kita akan menggunakan plugin jQuery Throttle / Debounce (http://benalman.com/projects/jquery-throttle-debounce-plugin/)

Throttle dan Debounce adalah teknik yang digunakan untuk membatasi jumlah eksekusi event dalam jangka waktu tertentu. Perbedaannya adalah, throttle membantu mengurangi waktu eksekusi default (1 milidetik) menjadi sekian milidetik yang dapat kita atur sendiri. Sedangkan debounce akan mengeksekusi event apabila pergerakan event berhenti dalam waktu sekian milidetik. Untuk mengetahui cara kerjanya, kita akan membuat sebuah file HTML yang berisi 3 textarea.


<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Demo jQuery Debounce</title>
<style>
	*{margin:0px auto;}
	html,body{font-family:"Arial", "Helvetica",sans-serif;}

</style>
</head>
<body>

<h1>Demo Event Limiting dengan Debounce / Throttle</h1>

<div style="background:#007700; color:#fff; padding:.5em 1em;">Mainkan scroll di masing-masing kotak (gerakan atas bawah) dengan cepat.</div>


<table width=100%>
	<tr>
		<td>
			<strong>1. Tanpa Debounce/Throttle</strong>
			<textarea class="none" style="height:200px; width:100%">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!</textarea>
			<input type="number" value=0>
		</td>
		<td>
			<strong>2. Throttle</strong>
			<textarea class="throttle" style="height:200px; width:100%">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!</textarea>
			<input type="number" value=0>
		</td>
		<td>
			<strong>3. Debounce</strong>
			<textarea class="debounce" style="height:200px; width:100%">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sapiente, iusto, aut, facere, consequatur similique reiciendis molestiae eveniet excepturi quidem veniam accusamus amet id eaque officiis explicabo voluptatem asperiores soluta aliquam accusantium tempora vel aspernatur debitis quo minima impedit quod cum! Esse, quasi sit delectus corporis sint sunt dicta beatae quisquam!</textarea>
			<input type="number" value=0>
		</td>

	</tr>
</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
/*
 * jQuery throttle / debounce - v1.1 - 3/7/2010
 * http://benalman.com/projects/jquery-throttle-debounce-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function(b,c){var $=b.jQuery||b.Cowboy||(b.Cowboy={}),a;$.throttle=a=function(e,f,j,i){var h,d=0;if(typeof f!=="boolean"){i=j;j=f;f=c}function g(){var o=this,m=+new Date()-d,n=arguments;function l(){d=+new Date();j.apply(o,n)}function k(){h=c}if(i&&!h){l()}h&&clearTimeout(h);if(i===c&&m>e){l()}else{if(f!==true){h=setTimeout(i?k:l,i===c?e-m:e)}}}if($.guid){g.guid=j.guid=j.guid||$.guid++}return g};$.debounce=function(d,e,f){return f===c?a(d,e,false):a(d,f,e!==false)}})(this);	
</script>


</body>
</html>

 

Dalam demo ini, kita akan mencoba mencatat jumlah event dipanggil di masing-masing textarea. Textarea.None adalah textarea yang akan dikaitkan pada event scroll biasa, Textarea.Throttle akan dikaitkan pada event scroll dengan pembatasan waktu eksekusi, dan Textarea.Debounce akan dikaitkan pada event scroll dengan pengecekan perhentian gerakan.


<script>
$(function(){
	$("textarea.none").on("scroll",function(){
		var ipt = $(this).next("input[type=number]");
		curr = ipt.val();
		curr++;
		ipt.val(curr);
	});

	$("textarea.throttle").on("scroll", $.throttle(100, function(){
		var ipt = $(this).next("input[type=number]");
		curr = ipt.val();
		curr++;
		ipt.val(curr);
	}));
	
	$("textarea.debounce").on("scroll", $.debounce(100, function(){
		var ipt = $(this).next("input[type=number]");
		curr = ipt.val();
		curr++;
		ipt.val(curr);
	}));
});
</script>

Apabila kode diatas sudah diterapkan dengan benar, maka hasilnya akan menjadi seperti ini : 

Throttle & Debounce
Kesimpulan : 
Teknik debounce dan throttling sangat baik digunakan untuk membatasi jumlah eksekusi event. Dalam penerapannya, teknik ini dapat kita terapkan untuk menghandle event yang memakan resource tinggi seperti scroll, keydown, hover, mouseover, dsb..
Semoga tutorial ini bermanfaat~

Note : untuk mendownload demo tutorial ini dapat mengakses dan Save As langsung di dev.tianrosandhy.com/debounce-throttle.php

Post Your Comment Here