Skip to content

Instantly share code, notes, and snippets.

@ldmarz
Last active August 19, 2018 18:17
Show Gist options
  • Select an option

  • Save ldmarz/f3436d87773c74071c507e93d52ed249 to your computer and use it in GitHub Desktop.

Select an option

Save ldmarz/f3436d87773c74071c507e93d52ed249 to your computer and use it in GitHub Desktop.
Example of how to use debounce from lodash, more information at http://ldmarz.com/mejora-la-velocidad-de-tu-javascript-con-debounce/
Just for naming purpose
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
.titulo {
color: #fff;
}
.container-result {
background: #fff;
border-radius: 4px;
padding: 20px;
font-size: 25px;
text-align: center;
transition: all 0.2s;
margin: 0 auto;
width: 300px;
margin-bottom: 20px;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
.container-result.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
.span-text {
color: #fff;
}
<h3 class="titulo">
Move the mouse over the div <br/>
</h3>
<span class="span-text">Debounce ? <input type="checkbox" id="checkbox" /> </span>
<div id="container-result" class="container-result" tabindex="1">
<p id="result">Un elemento</p>
</div>
// find elements
function writeDOM(e) {
// Imagine some slow/hard function
$("#result").text(`${e.clientX} - ${e.clientY}`);
}
const $checkBox = $('#checkbox');
const debouncedWriteDom = _.debounce(writeDOM, 100);
$("#container-result").mousemove(e => {
if ($checkBox.is(':checked')) {
debouncedWriteDom(e);
} else {
writeDOM(e);
}
});
name: Debounce example
description: Debounce some hard function
authors:
- Ldmarz
resources:
- https://code.jquery.com/jquery-3.3.1.min.js
- https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js
normalize_css: no
wrap: l
panel_js: 0
panel_css: 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment