JavaScript Debounce

by Taufik Nurrohman

HTML

<div class="left">
     <h3>Tanpa Debounce</h3>

    <div class="box" id="box-1">Gerakan pointer mouse di sini...</div>
</div>
<div class="right">
     <h3>Dengan Debounce</h3>

    <div class="box" id="box-2">Gerakan pointer mouse di sini...</div>
</div>
<div style="clear:both;"></div>

CSS

* {
    margin:0;
    padding:0;
    font:inherit;
    background-color:white;
    color:black;
}
body {
    padding:30px;
}
.left, .right {
    width:50%;
    float:left;
    font:normal normal 13px/1.4 Arial, Sans-Serif;
}
h3 {
    font-weight:bold;
    font-size:18px;
    margin:0 0 10px;
}
.box {
    height:200px;
    background-color:#456;
    border:2px solid black;
    color:white;
    padding:20px;
    margin:0 10px;
    overflow:auto;
}

JavaScript

var elem_1 = document.getElementById('box-1'),
    elem_2 = document.getElementById('box-2');

// Tanpa debounce
elem_1.onmousemove = function () {
    this.innerHTML += ' test!';
};

// Dengan debounce
var timer = null;
elem_2.onmousemove = function () {
    if (timer) clearTimeout(timer);
    timer = setTimeout(function () {
        elem_2.innerHTML += ' test!';
        timer = null;
    }, 300);
};