Skip to content

Instantly share code, notes, and snippets.

@hikarock
Created May 29, 2013 15:05
Show Gist options
  • Save hikarock/5671000 to your computer and use it in GitHub Desktop.
Save hikarock/5671000 to your computer and use it in GitHub Desktop.
setTimeoutでdebounce
* {
margin: 0;
padding: 0;
border: 0;
}
body {
background: #ffd;
font: 30px sans-serif;
}
<button>save</button>
var _timerId = null;
function save() {
var delay = 10 * 1000;
// 実行待ち状態でもう一度呼ばれたら予約してある処理をキャンセル
if (_timerId) {
console.log("cancel");
clearTimeout(_timerId);
}
_timerId = setTimeout(function () {
console.log("wait end");
_timerId = null;
// 超重い保存処理
}, delay);
}
function handler() {
console.log("wait start");
save();
}
$("button").on("click", handler);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment