JavaScript Throttle

by Taufik Nurrohman

HTML

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

    <div class="box" id="box-1">Gerakan pointer mouse di sini...</div>
</div>
<div class="right">
    	<h3>Dengan Throttle</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 throttle
elem_1.onmousemove = function () {
    this.innerHTML += ' test!';
};

// Throttle 1 detik sekali
var delay = 1000, // 1 detik
    previousCall = new Date().getTime(); // waktu kadaluarsa pertama
elem_2.onmousemove = function () {
    var time = new Date().getTime();
    // Bandingkan antara waktu terakhir kali eksekusi dengan waktu setiap kali event bekerja.
    // Jika selisihnya sudah mencapai/melebihi `delay`, sisipkan teks "test!"
    if ((time - previousCall) >= delay) {
        previousCall = time; // set ulang waktu kadaluarsa
        this.innerHTML += ' test!';
    }
};