Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save srajagop/b21eec7efe0e505fece5 to your computer and use it in GitHub Desktop.
Save srajagop/b21eec7efe0e505fece5 to your computer and use it in GitHub Desktop.
Example for Throttle and Debounce

Example for Throttle and Debounce

An example that contains sliders that show the difference between the throttle and debounce method of underscore

A Pen by Niklas on CodePen.

License.

<div class="normal">I'm a normal element</div>
<input type="range" min="0" max="100" data-for="normal" />
<div class="throttled">I'm a throttled element</div>
<input type="range" min="0" max="100" data-for="throttled" />
<div class="debounced">I'm a debounced element</div>
<input type="range" min="0" max="100" data-for="debounced" />
var resizeElements = function resizeElements (event) {
var target = $(event.target),
relatedTo = target.data('for');
$('.' + relatedTo).css('width', this.value + '%')
console.log(relatedTo);
}
$('[data-for="normal"]').on('input', resizeElements);
$('[data-for="throttled"]').on('input', _.throttle(resizeElements, 100));
$('[data-for="debounced"]').on('input', _.debounce(resizeElements, 100));
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
body {
font-family: 'Montserrat', sans-serif;
}
div {
background: #0092E0;
box-sizing: border-box;
color: #fff;
margin-bottom: 1em;
overflow: hidden;
padding: 1em;
text-overflow: ellipsis;
white-space: nowrap;
width: 50%;
}
[type="range"] {
margin-bottom: 2em;
width: 100%;
}
<link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment