Removing ‘<b/>’ with a userscript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I frequently use a website where some pages erroneously contain a singular <b/>, resulting in all following text being bold. I’m trying to write a userscript to get around this, but the following JS code doesn’t work:
document.body.innerHTML = document.body.innerHTML.replace(/<b\/>/g, '')
Why?

A nice and safe way to do this would be:
document.querySelectorAll('b').forEach(b => {
// const parent = b.parentNode;
const fragment = document.createDocumentFragment();
fragment.append(...b.childNodes);
b.replaceWith(fragment);
// (optional) to join consecutive textNodes
// parent.normalize();
});
setTimeout(() => {
document.querySelectorAll('b').forEach(b => {
const parent = b.parentNode;
fragment = document.createDocumentFragment();
fragment.append(...b.childNodes);
b.replaceWith(fragment);
parent.normalize();
});
}, 1000);
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pellentesque posuere neque, ac consectetur turpis porta vel. Nullam consequat mauris quis lectus porttitor, id vehicula lorem maximus. Nunc laoreet velit nisl. Nunc sit amet nulla egestas, <b>tincidunt magna sed, hendrerit ante.</b> Vestibulum elementum porttitor nisi quis commodo. Morbi gravida odio a eros pretium, at sagittis velit iaculis. Ut quis eleifend tortor. Etiam consectetur congue tempor. Pellentesque vel gravida velit. Maecenas quis urna ante. Morbi vel tellus eros.
</p>
<p>
Nulla scelerisque vitae lacus quis consequat. Donec volutpat efficitur diam non lobortis. Donec porttitor in lorem vitae iaculis. Suspendisse eu ligula a arcu ultrices scelerisque vitae at lacus. Fusce sodales, nunc ac tincidunt dignissim, velit felis pellentesque odio, ac mattis orci eros molestie est. Aliquam euismod cursus sem, nec convallis libero aliquam vel. Aliquam ut velit ornare risus sollicitudin convallis. <b>Etiam massa sem, facilisis vel hendrerit vitae, <b>dignissim fermentum nulla.</b> Nullam pellentesque ipsum eu egestas convallis.</b> Maecenas scelerisque vitae nisl at tempor. Etiam eu egestas nibh. Phasellus vitae consectetur velit, sed fringilla metus. Nunc vitae pellentesque arcu. Nullam eget felis id ligula molestie placerat. Aliquam gravida pulvinar posuere. Nullam non purus consequat, volutpat enim eu, convallis ante.
</p>
<p>
<b>Quisque egestas</b> enim sed felis scelerisque ultrices. Proin id justo vitae ante volutpat tristique a nec metus. Vivamus quis scelerisque nunc, vitae dictum nunc. Vestibulum ultrices sem sit amet facilisis ornare. Sed tellus libero, vestibulum molestie ultricies a, cursus a nisi. Suspendisse potenti. Vestibulum sed ante tortor. Suspendisse eu sem quis velit aliquam tempus. Vivamus eget vulputate est, nec fermentum sem. Suspendisse potenti. In nunc ante, tincidunt ut nunc id, tempor aliquam mi. Vestibulum dictum, mi sed tempus commodo, ex turpis aliquam felis, suscipit aliquet leo eros tempor nisi. Donec et suscipit risus. Proin vestibulum felis interdum tellus luctus, nec tempus turpis cursus. Curabitur lectus nibh, scelerisque ut magna sed, aliquet mollis risus. Sed pulvinar, felis at sodales porta, enim neque rhoncus nulla, eget ornare odio lectus facilisis dolor.
</p>
To support ES5 (not sure why you'd need to at this point), here's a more verbose alternative that also happens to be more efficient than above:
var nodes = document.getElementsByTagName('b');
for (var i = 0; i < nodes.length; i++) {
var b = nodes[i];
var parent = b.parentNode;
var fragment = document.createDocumentFragment();
for (var j = 0; j < b.childNodes.length; j++) {
fragment.appendChild(b.childNodes[j]);
}
parent.replaceChild(fragment, b);
// check for DOM level 2 support
if (typeof parent.normalize === 'function') {
// this step is not required
// just re-optimizes DOM layout
parent.normalize();
}
}
See:
document.querySelectorAll()
DocumentFragment
ChildNode.replaceWith()
ParentNode.append()
Node.childNodes
Node.normalize()

The dom can't contain a single <b/>, it must have a <b> before.
The correct regex would be :
document.body.innerHTML = document.body.innerHTML.replace(/<b\/?>/g, '')

Related

How to get the height of an element without its CSS?

My element has a CSS class that defines what the height of it should be.
.very-long-container {
height: 50px;
}
<div class="very-long-container">...</div>
I want to know the original height of that element, so not what is defined with CSS.
Well, my way of getting the height is to reset the CSS first, get the original height and then set the height with CSS again. Like this:
document.querySelector('.very-long-container').style.height = 'inherit';
console.log(document.querySelector('.very-long-container').offsetHeight);
document.querySelector('.very-long-container').style.height = '50px';
Since this is not the best practice, I am sure that there are better answers.
The container is 50px and will always be that if you tell it. When you remove the 50px from the CSS it will take the height of the children inside of it.
So one way of know what the actual height would be whenever there is no fixed height set is to either have another container inside of the container or to sum the height of all children inside of the container.
The former is the easiest to work out. If a child container does not have a fixed height, it will automatically take the height of the children inside of it, despite the outer container having a fixed height.
The example below uses the aforementioned technique. Reading the offsetHeight of the inner container. As a bonus it uses a ResizeObserver to update the height whenever the size of the inner container changes.
const innerContainer = document.querySelector('.inner-container');
let height = innerContainer.offsetHeight;
const resizeObserver = new ResizeObserver(entries => {
for (const { target } of entries) {
height = target.offsetHeight;
console.log(height);
}
});
resizeObserver.observe(innerContainer);
.very-long-container {
height: 50px;
overflow: hidden;
}
<div class="very-long-container">
<div class="inner-container">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam congue efficitur purus vel posuere. Nam eget tincidunt dolor, eu tempor neque. Aliquam ac ex urna. Ut scelerisque urna purus, tincidunt bibendum massa accumsan id. Mauris vitae cursus mi.
Phasellus imperdiet vel metus et ornare. Donec nulla justo, convallis sed lacus at, dapibus rhoncus neque. Cras velit erat, lacinia eu lectus lobortis, rhoncus congue ex. Curabitur lacus diam, dignissim at tortor ac, suscipit venenatis tortor. Fusce
tempus consectetur dui, vel placerat purus luctus nec. Morbi elementum, mi lacinia rhoncus vehicula, dolor dolor iaculis augue, id feugiat arcu tortor sed lectus. Quisque lacus justo, luctus sit amet finibus quis, pretium sed ex.
</p>
<p>
Morbi luctus neque non nunc placerat varius. Sed cursus scelerisque mi id interdum. Sed sodales orci ut laoreet imperdiet. Duis pretium erat ut libero consectetur ultrices. Aenean suscipit ultricies diam at pretium. Fusce pharetra lectus at lectus ornare,
sit amet lobortis libero lacinia. Quisque odio orci, ornare sed molestie non, fermentum at enim. Nam ut tortor enim. Nulla facilisi. Maecenas vehicula vitae felis ut mollis. Nam varius elementum felis, condimentum hendrerit velit elementum eu. Praesent
laoreet, turpis vel condimentum auctor, nisi erat viverra purus, sed gravida odio nulla nec urna.
</p>
<p>
Morbi sed enim ligula. Fusce vitae feugiat nunc. Sed vel velit orci. Nunc ut euismod ipsum. Cras sed velit nec lectus scelerisque sagittis. Fusce non nunc leo. Donec viverra eu felis sed molestie. Proin ut molestie libero, ut ultricies purus. Nullam dapibus
felis non vestibulum aliquam. Mauris quam mi, dictum eu nisi vitae, malesuada ultricies turpis. Donec vitae dolor leo. Nulla at dui eget eros molestie congue. Etiam imperdiet lobortis feugiat.
</p>
<p>
Maecenas enim magna, convallis vitae scelerisque at, lobortis vitae elit. Cras interdum ipsum non purus feugiat rhoncus. Fusce eu elit porttitor, aliquet libero at, dapibus massa. Suspendisse dignissim varius mauris, sed ullamcorper mauris interdum quis.
Proin viverra purus massa, in finibus magna faucibus ut. Nulla malesuada ipsum vel maximus vestibulum. Vestibulum molestie in dui fringilla interdum. Donec dignissim sapien nisl. Suspendisse aliquam elit turpis, at euismod mauris consectetur vel.
</p>
<p>
Suspendisse fermentum urna a arcu dignissim tincidunt. Nulla pellentesque orci vitae vulputate rutrum. Vestibulum interdum faucibus lectus vel vehicula. Suspendisse egestas dolor sit amet justo vehicula sodales. Integer fringilla eget erat id rhoncus.
Aenean luctus purus ut libero volutpat, viverra lobortis dui maximus. Integer sit amet aliquet nulla. In suscipit id orci sed tincidunt. Suspendisse pharetra suscipit tempus. Cras mattis a nibh eu porttitor. Donec nec iaculis metus. Pellentesque
molestie diam eu eleifend cursus. Suspendisse tincidunt, lorem quis pulvinar viverra, metus felis imperdiet nisi, ut dignissim velit urna nec odio. Quisque pulvinar turpis non ipsum mattis, a iaculis ipsum pellentesque. Vestibulum finibus sed sapien
quis faucibus. Vivamus tristique, neque id finibus ultrices, sapien elit consequat odio, placerat commodo magna odio id velit.
</p>
</div>
</div>

scrollIntoView() using smooth function on multiple elements in Chrome

element.scrollIntoView with behavior set to smooth is not working as I expect in Chrome. When it is used only on one element in a callstack, it works fine. But if it is used on multiple elements, only the last element will actually scroll.
This works fine in Firefox. Is there a workaround for this in Chrome?
const $ = (s) => document.querySelector(s)
const $$ = (s) => document.querySelectorAll(s)
const container = $(".container")
for (let i = 0; i < 2; i++) {
document.body.appendChild(container.cloneNode(true))
}
function scrollIntoView(behavior) {
for (const element of $$(".reveal")) {
element.scrollIntoView({
behavior,
block: "end"
})
}
}
$(".instant").addEventListener("click", () => scrollIntoView("instant"))
$(".smooth").addEventListener("click", () => scrollIntoView("smooth"))
$(".reset").addEventListener("click", () => {
for (const element of $$(".container")) {
element.scrollTo(0, 0)
}
})
.container {
max-height: calc(33vh - 12px);
overflow-y: auto;
}
.reveal {
color: red;
}
<button class="instant">
Instant
</button>
<button class="smooth">
Smooth
</button>
<button class="reset">
Reset
</button>
<div class="container">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed rhoncus elementum quam. Donec quis est volutpat, dapibus nisl at, consequat turpis. Quisque convallis nunc faucibus eros egestas, in faucibus neque fringilla. Duis aliquam, metus tempor dignissim
vestibulum, nulla elit lacinia lacus, vitae pulvinar augue diam et turpis. Aenean a velit sed elit dictum fringilla ut eu augue. Vestibulum hendrerit dolor mauris. Proin quis lacus a turpis posuere maximus. Sed lacus mauris, feugiat a iaculis porta,
lacinia vel eros. Integer tempor id tortor vitae fermentum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Etiam lobortis efficitur massa, eu elementum nulla eleifend ut. Quisque non erat iaculis, ornare erat non, interdum sapien. Suspendisse
sit amet interdum nisl, eu maximus libero. Fusce nisi nulla, iaculis eu est a, mattis tincidunt sem. Pellentesque non orci dapibus, dignissim ipsum a, finibus metus. Quisque placerat porta neque, eget finibus lectus tempus sed. Cras non gravida urna.
Morbi pretium mauris nec erat consectetur, vitae convallis lacus consectetur. Nam venenatis diam magna, sed venenatis nisl placerat viverra. Integer et mi pellentesque risus consectetur ultrices. Phasellus iaculis risus elementum, vulputate est sed,
consectetur diam. Phasellus lobortis felis purus, sit amet mattis elit pharetra ac. Nulla at viverra leo. Maecenas a condimentum magna. Maecenas porta tellus sit amet elit fermentum tincidunt. Donec ultricies blandit enim id mollis. Sed rutrum risus
sit amet posuere varius. Suspendisse suscipit maximus ligula eget egestas. Nullam lorem neque, viverra in sollicitudin ac, cursus nec purus. Aliquam placerat, arcu sit amet tincidunt consequat, ex est lacinia tellus, ac mattis nisl sapien at enim. Cras
lacinia libero eu eleifend sodales. Praesent a erat convallis, venenatis dui ut, semper sem. Vivamus tincidunt tempor neque, at congue lacus tincidunt et. Praesent consectetur, massa tristique laoreet sollicitudin, erat diam mattis nibh, nec consequat
mauris odio ut est. Integer pharetra arcu at finibus congue. Proin pellentesque fringilla blandit. Suspendisse egestas interdum nisl. Nulla facilisi. Quisque dapibus odio risus. Donec non orci dapibus risus pellentesque cursus vestibulum vel arcu. Proin
volutpat tellus sed elit auctor, sit amet tincidunt ante cursus. Donec faucibus sit amet libero sit amet lobortis. Pellentesque posuere nisl vitae pharetra vestibulum. Mauris et lobortis libero, vel facilisis metus. Duis eu venenatis dui. Fusce gravida
nibh odio, quis ullamcorper nibh rutrum sed. In dapibus, nulla non auctor egestas, nisi augue venenatis quam, et finibus lorem dui non turpis. Nullam arcu diam, mattis at erat ac, viverra lobortis felis. In in nisi magna. Ut ut ultrices velit, quis
vehicula libero. Proin dictum metus vel ante lobortis, in placerat magna ornare. Etiam vulputate metus felis, sed fringilla magna convallis vitae. Curabitur non pulvinar ante, eget molestie nibh. Quisque facilisis, diam sed dapibus blandit, ex urna
vulputate est, non auctor risus dui nec augue. Donec pretium laoreet est, tempor faucibus tortor laoreet ac.
<span class="reveal">Revealed!</span>
</div>
As per this draft at drafts.csswg.org, it is not possible to use the smooth function for scrolling multiple elements simultaneously;
When a user agent is to perform a scroll of a scrolling box box, to a given position position, an associated element element and optionally a scroll behavior behavior (which is "auto" if omitted), the following steps must be run:
Abort any ongoing smooth scroll for box.
If the user agent honors the scroll-behavior property and one of the following are true:
behavior is "auto" and element is not null and its computed value of the scroll-behavior property is smooth
behavior is smooth
...then perform a smooth scroll of box to position. Otherwise, perform an instant scroll of box to position.
Your options are:
Scroll the elements one by one using the native smooth function.
Use different API or library to animate the elements.
Functionally design the thing differently, so they don't need to scroll simultaneously.

Get text selection after time elapsed from webpage

I want to get the text selected and also the DOM element along with where the ending of the text selection offset was in the webpage some seconds after the selection completed.
So like you highlight some text and if in 3 seconds that text is still highlighted, then I want to run some code that has as parameters the highlighted text and the DOM element that was nearest ancestor of the text.
I found there is this selectstart event,
https://developer.mozilla.org/en-US/docs/Web/API/Document/selectstart_event
and also the selectionchange event but I don't see a selectend event.
Some ideas were along these lines:
document.addEventListener('selectionchange', () => {
// if (Math.abs(Date.now().getTime() - process_request_start.getTime()) / 1000 <= 5
// if (is_processing_request === true) {
// return;
// }
setTimeout(() => {
if (is_processing_request === true) {
return;
} else {
is_processing_request = true;
console.log(document.getSelection());
is_processing_request = false;
}
}, 5000);
});
So I am looking for elegant code examples that provide/emulate a selectend, I had some working ideas using setTimeout but looking for any other solutions, prefer working code and not assuming any Jquery/libs, just native DOM environment.
For this particular problem, clearTimeout is your friend! You just cancel the timeouts until the time has elapsed (I shortened it to 2 seconds for this example):
let waiting = null;
document.addEventListener('selectionchange', () => {
if (waiting) clearTimeout(waiting);
waiting = setTimeout(() => {
console.log(document.getSelection().toString());
waiting = null;
}, 2000);
});
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus viverra diam quis aliquet pulvinar. Donec fringilla feugiat elit, vitae pretium turpis suscipit et. Integer tempus massa pellentesque arcu sagittis iaculis. Interdum et malesuada fames ac ante ipsum primis in faucibus. Duis faucibus vestibulum tempus. Morbi at dolor rutrum, malesuada ex sed, tempor nisl. Aenean viverra accumsan accumsan. Suspendisse dignissim augue tellus, quis sollicitudin enim dignissim nec. Nunc mollis vehicula nibh, sed suscipit diam tristique vitae. Nam efficitur massa quis ultrices lacinia. Nunc consequat interdum nunc, vel luctus risus faucibus vel. In arcu diam, bibendum ac enim vel, dignissim vehicula quam. Donec non justo scelerisque, hendrerit est rhoncus, consectetur mi. Pellentesque a lorem eget ex placerat sodales eget sit amet metus. Phasellus aliquam vitae neque vel suscipit.
In in nisl tristique, dictum justo ut, consectetur risus. Suspendisse congue dignissim orci, scelerisque accumsan massa ornare vel. Sed finibus ultrices felis, eu ultrices magna consectetur nec. Proin eu fringilla risus. Cras id posuere ex, sed porta dui. Integer id dolor massa. Cras dui ante, congue a odio non, pulvinar faucibus nisi. Nunc in ex non quam rutrum tempus sit amet ac neque. Vestibulum blandit vulputate massa, ut tincidunt magna dictum id. Vivamus laoreet auctor sollicitudin. Duis eu quam ac lacus faucibus imperdiet sodales eu nisl. Integer auctor commodo turpis, a ultricies sem lacinia iaculis.
Quisque id mattis neque, ut dignissim lectus. Curabitur ex libero, rutrum sed massa a, ultricies fringilla justo. Pellentesque in interdum felis, et aliquet ante. Praesent mauris leo, pretium quis lectus non, ultricies elementum neque. Nam suscipit ullamcorper neque sed iaculis. Maecenas placerat nisl et convallis hendrerit. Suspendisse molestie erat non leo cursus, in maximus sem facilisis. Ut non magna quis purus pellentesque auctor sed sed lorem. Aenean sed iaculis metus, at bibendum libero. Pellentesque in est nec ipsum maximus rutrum in vel dui. Duis porta laoreet dolor, aliquet eleifend mi dapibus consequat.
Mauris posuere tempus libero ut ullamcorper. Aenean ac accumsan enim. Quisque ex felis, pretium euismod dui et, euismod malesuada sapien. Etiam et tempus nulla. Quisque aliquet aliquet risus dapibus vestibulum. Etiam blandit leo odio, ac fringilla ante molestie nec. Sed commodo ex a finibus commodo.
Fusce sed fringilla tellus. Fusce id sagittis ipsum. Vivamus lacus neque, interdum et enim et, ultricies consectetur quam. Aenean lacus augue, placerat id odio vitae, imperdiet sodales mauris. In ornare est sit amet vestibulum interdum. Fusce ultrices, mi non mollis condimentum, est ligula dictum arcu, sed hendrerit magna dolor et ex. Morbi faucibus interdum mattis. Duis vel luctus sem, vitae porta elit. In gravida, leo at laoreet iaculis, mi odio ultrices nulla, sed dictum metus enim ac mauris. Sed odio est, consequat vel turpis et, accumsan accumsan libero. Maecenas nec luctus quam. Aenean et lobortis libero, quis pulvinar felis. Vestibulum sed dolor ornare, ultrices justo non, aliquam felis. Mauris sagittis rutrum mi, sit amet imperdiet lorem luctus non. Praesent ac tortor maximus, facilisis diam sit amet, rutrum nunc. Fusce sit amet lectus pretium, vehicula arcu laoreet, elementum justo.</div>

How to access element from this.event.path?

I basically want to access all the properties of an element that you get when say, that element is a target to an event. We do this via this.event.target to get access to all its properties.
What I want to do is search for scrollTop key of elements in the path of an event but all I am returned is their names instead of their equivalent JS objects.
Here's my try:
const viewport = this.event.path.filter(element => element.scrollTop) || { scrollTop: 0 };
But this just doesn't work and returns me an empty array.
you're not getting the scrollTop values because filter return the array containing all the elements having the properity scrollTop : do as following :
const viewport = this.event.composedPath().filter(element => element.scrollTop).map(e => { return e = {
//whatever you want to keep
scrollTop: e.scrollTop
}})
Here's a simple example to extract the scrollTop values from it with map
document.querySelector('html').addEventListener('click',function(e) {
let paths = e.composedPath().map(e => { return e.scrollTop || 0 })
console.log(paths)
});
div {
overflow-y: scroll;
height: 20px;
}
<div>
<span>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur pretium sed quam sed faucibus. Sed dictum enim non tortor egestas, sagittis mattis sem hendrerit. Duis quis massa turpis. Fusce consectetur facilisis lectus nec elementum. Praesent porttitor massa non enim bibendum, eu interdum lacus vehicula. Vestibulum efficitur felis sit amet ipsum venenatis interdum. Sed vulputate nibh id mi egestas, eu rutrum tellus dignissim. Sed suscipit risus condimentum libero pulvinar venenatis. Maecenas semper, erat eget dictum egestas, nisl urna finibus quam, a fermentum magna ante vel erat. Integer sed neque tristique, bibendum nisl et, pretium augue. Duis malesuada odio vitae commodo venenatis. Nunc consequat libero ac velit tempus sollicitudin. Sed scelerisque velit sem, ac pellentesque tellus rutrum eget. Aliquam convallis, ipsum id consectetur tempor, nibh odio fermentum orci, vitae imperdiet felis arcu vel elit. Sed venenatis et erat eget scelerisque. Aliquam consectetur nibh eu augue dignissim, a vestibulum ligula facilisis.
Quisque tincidunt in nulla ut placerat. Nullam posuere massa et urna eleifend consectetur. Praesent in odio mauris. Quisque pellentesque ante vitae justo consequat, vel posuere sapien lacinia. Aliquam varius diam nec purus scelerisque lobortis. Donec nisi mi, imperdiet posuere orci in, lobortis egestas purus. Aenean luctus egestas eleifend. Donec semper lectus nunc, eget consectetur nulla commodo vel. Aliquam erat volutpat. Quisque sodales enim sed diam pretium, eget finibus felis interdum. Mauris mattis id velit quis tincidunt. Fusce et pellentesque felis. Proin fermentum, est sed malesuada egestas, lorem nisl luctus mi, non tempor mi leo id nunc. In viverra rhoncus pulvinar. Duis dictum sem ac nisi fermentum, non iaculis eros convallis.
Vestibulum pharetra neque vitae auctor fermentum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi eu erat sed ante cursus congue quis nec metus. Donec et erat sed quam faucibus pellentesque. Donec eu orci id justo dignissim tempor at sit amet dui. Curabitur varius lobortis pellentesque. Duis et diam sed ligula laoreet maximus in vel ex. Sed consequat eleifend libero a accumsan. Maecenas convallis tellus lobortis tristique vulputate. Morbi luctus a nisl ac accumsan. Integer dignissim orci et rhoncus porta.
Curabitur lacinia ullamcorper turpis in tincidunt. Nulla facilisi. Sed blandit ultricies arcu, vitae luctus nisi suscipit non. Fusce iaculis dapibus risus. Praesent turpis purus, sodales eget condimentum nec, vehicula id erat. Cras placerat velit justo, non imperdiet quam efficitur in. Fusce sit amet nisl sed purus vestibulum interdum. In felis mi, finibus non sagittis ut, accumsan a velit.
Nunc et ullamcorper mi. Donec vulputate tortor ante, in consequat enim facilisis condimentum. Nullam fermentum, libero ac iaculis tincidunt, dui nibh varius enim, in sollicitudin elit arcu eget libero. Quisque tincidunt mauris ex, sed congue augue faucibus at. Phasellus accumsan urna id enim ullamcorper suscipit. Pellentesque id quam a enim hendrerit dictum. Etiam sit amet dapibus justo, at sollicitudin urna. Etiam sodales efficitur urna, tempor ullamcorper tellus blandit sit amet. Ut magna magna, euismod et viverra suscipit, tristique posuere enim. Phasellus augue ex, viverra a pretium vel, porttitor a turpis. In placerat lectus eu suscipit sodales. Nam at placerat odio. Vivamus ullamcorper fringilla quam in iaculis. Maecenas id viverra nibh. Nunc lorem nunc, auctor non augue a, aliquam dictum lorem. Phasellus pretium nibh in nunc fermentum scelerisque et vel turpis.
</span>
</div>
scroll the text and click on it

Throttling with Lodash doesn't work

I want to use Lodash's throttle to have fewer function invokes on scroll. My code is as follows:
window.addEventListener('scroll', _.throttle(() => { console.log('bam'); }), 1000);
Unfortunately, this doesn't work - I am getting bam-ed all the time, and not every one secound.
What can I do?
CodePen: http://codepen.io/tomekbuszewski/pen/oxeOXy?editors=1111
The _.throttle function should only be generated once and not every time the event fires
var callback = _.throttle(() => { console.log('bam')}, 10000);
window.addEventListener('scroll', callback);
div {
height : 100px
}
div > div {
height : 1000px
}
<script src="https://cdn.jsdelivr.net/lodash/4.6.1/lodash.min.js"></script>
<div>
<div></div>
</div>
the console.log("bam") called once every 10 sec
There is a mistake in your code
window.addEventListener('scroll', _.throttle(() => { console.log('bam'); }, 1000));
var f = function() {
console.log("bam");
}
window.addEventListener('scroll', _.throttle(f, 1000));
Simple, Efficient, And Low-Overhead Soution
You do not need lodash for a decent throttle function. The purpose of a throttle function is to reduce browser resources, not to apply so much overhead that you are using even more. Also, my different uses for throttle functions require many different circumstances for them. Here is my list of things that a 'good' throttle function needs that this one has.
Minimal overhead.
Immediate function call if it has been more than interval MS since the last call.
Avoiding executing function for another interval MS.
Delaying excessive event firing instead of dropping the event altogether.
Updates the delayed event when need be so that it doesn't become 'stale'.
Prevents the default action of the event when the throttled function is delayed.
Be able to remove the throttle event listener listener.
And, I believe that the following throttle function satisfies all of those.
function throttle(func, alternateFunc, minimumInterval) {
var executeImmediately = true, freshEvt = null;
return function(Evt) {
if (executeImmediately) { // Execute immediatly
executeImmediately = false;
setTimeout(function(f){ // handle further calls
executeImmediately = true;
if (freshEvt !== null) func( freshEvt );
freshEvt = null;
}, minimumInterval);
return func( Evt );
} else { // Delayed execute
freshEvt = Evt;
if (typeof alternateFunc === "function") alternateFunc( Evt );
}
};
}
N.B.: removeEventListener can only remove the exact function passed to addEventListener. If you sent a wrapped function to addEventListener, then removeEventListener requires this same wrapped function, not the original function. Thus, the following does not work.
function clickFunctor(){ /*...*/ }
// This code throttles clickFunctor to 500ms
var throttledFunctor = throttle(clickFunctor, null, 500); // WORKS
addEventListener("click", throttledFunctor, false); // WORKS
// ONLY this removeEventListener works
removeEventListener("click", throttledFunctor, false); // WORKS
// For example, this removeEventListener does not work
removeEventListener("click", throttle(clickFunctor, null, 500), false); // FAILS
// This removeEventListener also does not work
removeEventListener("click", clickFunctor, false); // FAILS
If you need wrappers around addEventListener and removeEventListener so that they work properly, then you can use the functions below.
var tfCache = []; // throttled functions cache
function listen(source, eventName, func, _opts){
var i = 0, Len = tfCache.length, cF = null, options = _opts || {};
a: {
for (; i < Len; i += 4)
if (tfCache[i] === func &&
tfCache[i+1] === (options.ALTERNATE||null) &&
tfCache[i+2] === (options.INTERVAL||200)
) break a;
cF = throttle(func, options.ALTERNATE||null, options.INTERVAL||200);
tfCache.push(func, options.ALTERNATE||null, options.INTERVAL||200, cF);
}
source.addEventListener(eventName, cF || tfCache[i+3], _opts);
return cF === null; // return whether it used the cache or not
};
function mute(source, eventName, func, _opts){
var options = _opts || {};
for (var i = 0, Len = tfCache.length; i < Len; i += 4)
if (tfCache[i] === func &&
tfCache[i+1] === (options.ALTERNATE||null) &&
tfCache[i+2] === (options.INTERVAL||200)
) {
source.removeEventListener(eventName, tfCache[i+3], options);
return true;
}
return false;
}
listen and mute will work for any event on any instance that inherits from EventTarget, such as an Element's blur/focus, 'click' on the window, XMLHttpRequest's onprogress, FileReader's onprogress, [etc.].
Example usage:
var docElement = document.firstElementChild;
docElement.style.transition = "background .667s linear";
function whenTheDocumentScrolls() {
var scrollTop = docElement.scrollTop || -docElement.getBoundingClientRect().top;
var bgColor = "#fff";
if (scrollTop < 1600) bgColor = "#9f9";
else if (scrollTop < 3000) bgColor = "#ff9";
else if (scrollTop < 3600) bgColor = "#f9e";
else if (scrollTop < 5600) bgColor = "#c8f751";
else if (scrollTop < 7200) bgColor = "#68f";
else if (scrollTop < 9200) bgColor = "#3fb";
docElement.style.backgroundColor = bgColor;
}
whenTheDocumentScrolls(); // Compute the background color right now
var scrollListenerOptions = {
passive: true,
capture: false,
// ALTERNATE: function(){ /*...*/ },
INTERVAL: 500 // check at most twice a second
};
function throttle(func, alternateFunc, minimumInterval) {
var executeImmediately = true, freshEvt = null;
return function(Evt) {
if (executeImmediately) { // Execute immediatly
executeImmediately = false;
setTimeout(function(f){ // handle further calls
executeImmediately = true;
if (freshEvt !== null) func( freshEvt );
freshEvt = null;
}, minimumInterval);
return func( Evt );
} else { // Delayed execute
freshEvt = Evt;
if (typeof alternateFunc === "function") alternateFunc( Evt );
}
};
}
var tfCache = []; // throttled functions cache
function listen(source, eventName, func, _opts){
var i = 0, Len = tfCache.length, cF = null, options = _opts || {};
a: {
for (; i < Len; i += 4)
if (tfCache[i] === func &&
tfCache[i+1] === (options.ALTERNATE||null) &&
tfCache[i+2] === (options.INTERVAL||200)
) break a;
cF = throttle(func, options.ALTERNATE||null, options.INTERVAL||200);
tfCache.push(func, options.ALTERNATE||null, options.INTERVAL||200, cF);
}
source.addEventListener(eventName, cF || tfCache[i+3], _opts);
return cF === null; // return whether it used the cache or not
};
function mute(source, eventName, func, _opts){
var options = _opts || {};
for (var i = 0, Len = tfCache.length; i < Len; i += 4)
if (tfCache[i] === func &&
tfCache[i+1] === (options.ALTERNATE||null) &&
tfCache[i+2] === (options.INTERVAL||200)
) {
source.removeEventListener(eventName, tfCache[i+3], _opts);
return true;
}
return false;
}
listen(window, "scroll", whenTheDocumentScrolls, scrollListenerOptions);
listen(document.getElementById("stop-scrolling"), "click", function(){
mute(window, "scroll", whenTheDocumentScrolls, scrollListenerOptions);
}, {passive: true});
<button id="stop-scrolling" style="position:fixed;bottom:0;right:0">Remove the scroll listener</button>
<div style="font-size:1.4em;line-height:1.8;white-space:pre-wrap">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi semper facilisis leo quis imperdiet. Maecenas vitae malesuada nibh. Donec volutpat nunc in eros pretium vulputate. Curabitur lorem ipsum, tincidunt at hendrerit sed, venenatis vitae nibh. Duis varius felis vitae sem consequat varius. Interdum et malesuada fames ac ante ipsum primis in faucibus. Integer semper eget dolor et egestas. Proin nec ipsum rhoncus, pellentesque quam non, vestibulum augue. Curabitur et diam non est tempor dignissim. Fusce tempor nisl a ligula sagittis, eget condimentum magna iaculis. Vestibulum vulputate mauris eget mi semper, eget mattis orci tincidunt. Phasellus sit amet egestas turpis. Aliquam aliquet facilisis dolor, ultrices mollis risus mollis vulputate. Praesent id ligula at mi faucibus ornare. Fusce at tristique dui. Nullam pellentesque, augue eget tristique egestas, est metus euismod odio, a convallis lacus lectus non massa.
Nullam a fringilla turpis. Mauris in ultricies est. Nam faucibus, nunc eu suscipit volutpat, est augue congue velit, fermentum ornare nibh erat ac ex. Sed ut neque auctor, facilisis arcu in, molestie leo. Praesent vestibulum lacinia sapien, ac porta ligula porttitor et. Vestibulum nec ante libero. Sed vel velit elit. Praesent tristique bibendum consectetur. Vestibulum pretium tellus sapien, eu vulputate mi condimentum ut. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;
Vestibulum semper elit risus, id fringilla enim gravida non. In in tellus quis nulla commodo volutpat. Sed tristique, magna eu sagittis porttitor, quam neque varius ante, ac mattis elit ex vitae nisl. Fusce sed justo vitae elit tempus porta. Donec nisl justo, bibendum nec dolor vitae, venenatis elementum justo. Nulla egestas quis tellus non vehicula. Proin vel lobortis felis. Quisque tempus eu elit non porta. Cras eleifend nisl nec vehicula tristique. Integer et pellentesque urna. In eu magna turpis. Vivamus vitae diam nec nulla vulputate pharetra eget vel leo. Praesent et tortor sed purus commodo finibus sit amet id ipsum. Pellentesque diam elit, condimentum et varius eu, elementum vitae quam.
Cras felis tellus, auctor non consectetur non, pharetra sed purus. In ut condimentum risus, eu ornare augue. Aliquam eu ex augue. Nunc tincidunt, libero a pellentesque dignissim, metus dui posuere mauris, eu iaculis purus dolor non quam. Donec venenatis tellus ut nisi tristique, sed egestas ipsum auctor. Integer gravida mollis nulla porta pretium. Proin vel dolor nisi. Suspendisse ut lacinia turpis. Donec lacinia lorem mollis ante pretium convallis. Aliquam erat volutpat. Donec vel porta libero. Donec eget arcu id risus fringilla finibus. Duis pulvinar hendrerit metus id porta. Maecenas et nulla in enim scelerisque tempus vel ut massa. Ut luctus placerat ipsum, sit amet pharetra nunc faucibus id.
Phasellus varius tortor a mi fermentum porttitor. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Maecenas mollis varius ante, non blandit ex cursus scelerisque. Vivamus sodales, diam at aliquam blandit, diam metus gravida lectus, non auctor augue felis ut justo. Proin in volutpat neque, id tempus arcu. Aenean vestibulum consequat leo, in tincidunt orci semper eu. Integer blandit vehicula consequat.
Donec accumsan purus quis sem dapibus aliquet. Etiam hendrerit sem eget tellus facilisis venenatis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Suspendisse vel consequat est. Sed quis convallis tellus. Vivamus quis semper odio. Mauris quis interdum ligula. Praesent cursus ante at libero sollicitudin, at varius nunc dapibus. Vivamus augue nisi, cursus in enim ut, eleifend hendrerit neque. Quisque rhoncus nibh a velit volutpat volutpat. Praesent a purus enim. Donec id fringilla nibh.
Pellentesque lectus turpis, auctor vel sem a, consequat rutrum odio. Mauris congue erat commodo, consectetur ante at, rutrum quam. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ut neque vel est rutrum pellentesque. Maecenas sem est, dapibus vitae nisi non, tempor tincidunt libero. Aenean ornare auctor tellus et molestie. Phasellus vel efficitur leo. Phasellus quis venenatis lectus. Nam ac neque quis dolor tristique gravida. Fusce sem dolor, suscipit non aliquam sed, cursus faucibus turpis. Integer feugiat, nulla ut vestibulum fringilla, velit dui rhoncus quam, a ullamcorper sapien libero ut quam. Phasellus ornare posuere libero, eu venenatis nunc iaculis nec. Etiam sed malesuada ante.
Morbi consequat risus sit amet tellus lobortis convallis ut mollis arcu. Donec suscipit mollis lectus, vitae ullamcorper sem aliquam ac. Aliquam sed erat id eros malesuada aliquam. Nunc semper felis sed ligula ullamcorper congue. Ut nec cursus libero, a posuere ligula. Proin luctus laoreet mi, ac semper lectus convallis nec. Maecenas eu egestas mi. Etiam varius ex eget tincidunt auctor.
Curabitur bibendum quam id ligula lacinia, quis molestie lacus vestibulum. Etiam dapibus lacus nulla, quis luctus justo tempus sed. Praesent mi enim, efficitur quis congue vestibulum, molestie non odio. Donec nibh ex, elementum vitae sodales quis, pulvinar vitae tortor. Morbi et egestas velit, eget congue nibh. Vestibulum fringilla mi leo. Curabitur cursus viverra mauris, sed auctor odio tristique eget. Suspendisse a ipsum tellus. Etiam eleifend vel sapien non consectetur. Mauris ac felis mauris. Donec fermentum eros sit amet ex placerat, id faucibus nisl lacinia. Vivamus eget dui vitae nisl commodo feugiat vitae ac ante. Nunc ullamcorper eros id massa sagittis, ac gravida felis semper. In hac habitasse platea dictumst.
In hac habitasse platea dictumst. Suspendisse potenti. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec vitae placerat ligula. Fusce malesuada mi et arcu pellentesque ornare. Fusce cursus, ipsum non gravida scelerisque, libero tortor sagittis elit, ac accumsan justo est sed ligula. Nam condimentum leo est. Vivamus hendrerit finibus metus quis cursus. Quisque consequat ipsum vitae justo volutpat ultricies. Nullam eget nisi quis sapien tempor scelerisque sit amet vel tellus. Vivamus euismod ultrices nisi a iaculis. Nam augue dui, aliquam et leo et, convallis imperdiet velit. Sed vestibulum eget quam eu fringilla. Suspendisse ac nunc ac ligula interdum congue et eget libero. In mollis dui sed mi finibus finibus.
Phasellus scelerisque, lectus in vulputate egestas, sem leo bibendum mauris, a tincidunt risus quam eu ante. Nulla placerat nibh et velit volutpat tincidunt. Ut luctus elementum massa, eget finibus tortor tincidunt at. Curabitur quis sagittis velit. Etiam finibus, quam vitae blandit vehicula, massa enim faucibus nisl, a aliquet purus justo tristique tortor. Sed fringilla tincidunt consequat. Mauris a tellus ultricies, tempus tortor nec, auctor est. Nulla feugiat nisl urna, a pulvinar erat consectetur condimentum. Interdum et malesuada fames ac ante ipsum primis in faucibus. Quisque in ultrices mi. Donec non sapien varius, tempor quam in, semper dui. Pellentesque aliquam sapien eu quam pellentesque pretium. Cras hendrerit dolor et libero semper, eget vestibulum quam tristique. Aliquam lobortis lacus vel purus mollis maximus. Nam vel imperdiet nunc, sit amet faucibus eros. Donec viverra varius volutpat.
Sed quis mollis dolor, et posuere eros. In eu quam orci. In vitae ante sed nisl vulputate ornare. Nullam quis ipsum molestie, laoreet elit quis, commodo tellus. Donec volutpat, velit at ornare fermentum, ipsum lectus convallis nisi, sed pharetra tortor tortor eget nisl. Vestibulum porta condimentum aliquet. Cras malesuada tellus erat, id auctor lorem pulvinar sed. Etiam non arcu suscipit, interdum sem eu, dapibus est.
Pellentesque tincidunt sem varius arcu semper lacinia. Suspendisse nunc felis, aliquet vel ullamcorper vitae, malesuada at dui. Vestibulum hendrerit neque sed sodales placerat. Praesent pulvinar massa eu risus facilisis placerat. Quisque tincidunt est sed mauris placerat, id viverra risus vulputate. Aenean in iaculis justo, et suscipit ligula. Aliquam efficitur in arcu vel vehicula. Suspendisse vitae dui magna. In dictum, nibh eget eleifend fermentum, sapien ex pharetra lorem, id dignissim lectus ipsum non nibh. Praesent at dignissim orci.
Sed ante nisi, commodo et metus ac, feugiat commodo nisi. Cras ut ligula sed augue dignissim gravida ut non mauris. Nullam laoreet diam at ligula luctus finibus. Nunc porta diam sit amet pharetra lacinia. Donec luctus sodales mauris, eu bibendum nisl tempus at. Donec sed pharetra nisi. Quisque sodales ligula nec eros placerat ultricies. In sit amet scelerisque tellus, quis sollicitudin ligula. Curabitur blandit ligula non odio facilisis, vel euismod ligula tempor. Nunc ligula arcu, mollis et metus eu, ullamcorper volutpat risus. Ut sem dolor, dignissim vitae fermentum malesuada, tincidunt aliquam ex. Sed placerat diam ligula, ac vehicula nunc eleifend vel. Nulla facilisi. Mauris in lectus non tortor lacinia vestibulum ut ut turpis.
Fusce gravida massa eget tincidunt malesuada. Integer sagittis quam non augue sodales viverra. Vestibulum luctus lectus sed eros molestie, ac congue leo fermentum. Mauris id urna sagittis, accumsan urna ac, posuere neque. Etiam molestie odio lobortis purus imperdiet venenatis. Ut pretium elementum velit, quis luctus massa sodales eu. Suspendisse varius at velit suscipit maximus. Pellentesque gravida ante a vehicula faucibus. Proin tincidunt scelerisque vestibulum.
Pellentesque varius semper metus, dignissim maximus elit hendrerit vel. Donec lobortis, tellus nec dictum pellentesque, nisl nisl ullamcorper erat, sit amet interdum nunc est sit amet lacus. In varius varius turpis vel facilisis. Vivamus ac viverra sem, vel scelerisque felis. Etiam eget nunc in nibh tempor dictum. Pellentesque dapibus auctor ante nec sollicitudin. Integer auctor mi tristique lectus convallis pretium. Cras aliquam, massa tempus molestie viverra, massa orci interdum ex, et dapibus justo massa eu arcu. Sed elementum pulvinar turpis, sed congue lorem tincidunt et.
Nam egestas felis orci, facilisis auctor urna sollicitudin ac. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis non euismod arcu. Aenean rhoncus ipsum ut neque finibus, ut pharetra dolor maximus. Pellentesque quam est, vestibulum non mattis id, luctus ut enim. Nam tempor lacus ut suscipit sagittis. Sed egestas id nisi quis tempus. Aenean non cursus quam, nec dignissim augue. Curabitur in placerat quam, in aliquet dui. Curabitur egestas, arcu nec auctor tempor, nibh lectus sollicitudin ligula, a malesuada mauris eros in orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec varius consequat dolor in pretium. Sed molestie tempor lectus. Curabitur consequat tristique risus, ac tempor ligula tristique ac. Cras porta blandit pretium. Donec vel enim nunc. Pellentesque quis bibendum dui, ac gravida orci. Donec sollicitudin massa in leo iaculis consequat.
Nulla at libero ullamcorper turpis venenatis interdum. Pellentesque gravida ante at nisl dignissim, vel consequat leo bibendum. Curabitur id turpis libero. Phasellus nec sapien magna. Quisque rhoncus sem in vulputate tempus. Nullam gravida eget purus ut imperdiet. Curabitur bibendum dapibus magna id ultricies. Sed vestibulum volutpat ante, sed porttitor ante porta in. Sed vitae eros dui. Sed sit amet nunc odio.
In cursus, est vitae fermentum facilisis, sapien felis accumsan erat, eu pretium ligula neque at orci. Cras at lorem sit amet enim finibus hendrerit ac lobortis est. Aenean nec dictum nulla. Vivamus scelerisque porttitor nisi, quis bibendum massa commodo et. Fusce nec dapibus purus, vitae sagittis nisl. Vivamus consectetur orci rutrum orci aliquam viverra. Morbi sodales elit at gravida imperdiet. Pellentesque sit amet felis sit amet orci venenatis gravida. Phasellus iaculis augue vitae laoreet lobortis.
Maecenas bibendum ultrices gravida. In eu tincidunt libero, quis tempus velit. Suspendisse placerat nisl magna, eu fringilla nunc luctus malesuada. Vestibulum sit amet orci hendrerit tortor pharetra lobortis ut at lacus. Cras erat metus, pretium sed metus ut, interdum posuere nisi. Nullam dolor sem, facilisis sed ex at, feugiat gravida lacus. Sed pellentesque mauris arcu, sit amet finibus nisi pulvinar non. Praesent metus felis, viverra quis libero in, sagittis vehicula ex. Phasellus a consectetur eros. Sed consectetur interdum sollicitudin. Donec sollicitudin venenatis arcu ultrices vehicula. Maecenas dolor urna, placerat id justo at, laoreet maximus enim. Integer porta odio ut purus interdum, at malesuada nisi tempus. Nullam vel cursus nulla. Mauris vehicula gravida sem. Nulla facilisi.
Etiam quis nisi at nibh varius tempor. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus venenatis massa laoreet varius blandit. Etiam gravida elit in pulvinar tincidunt. Donec rutrum neque in consectetur dignissim. Vestibulum nec lorem sed augue pretium fermentum. Morbi mattis libero purus, eget accumsan massa accumsan vel.
Nunc ullamcorper massa augue, nec bibendum metus fringilla suscipit. Donec iaculis non nulla eu sodales. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nam dapibus justo odio, at mollis nulla mollis dignissim. Suspendisse mollis, purus sed accumsan tristique, ex quam accumsan mauris, vitae tincidunt turpis magna in quam. Duis vel iaculis nibh. Praesent imperdiet diam at felis cursus commodo. Vestibulum sodales dapibus lacinia. Cras vitae eros ultricies, posuere purus eget, varius arcu. Nulla sodales mauris imperdiet dui bibendum, eu egestas lacus porttitor. Vivamus urna dolor, fermentum sit amet odio id, pharetra venenatis risus. Nunc id tortor metus. Quisque ultrices laoreet ante, a commodo libero dignissim gravida.
Sed bibendum ultricies rutrum. Aliquam ornare lacinia commodo. In dapibus nulla id fringilla convallis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Etiam mattis laoreet interdum. Proin id nibh purus. Aenean nisi dui, imperdiet id lobortis vel, faucibus aliquam dui. Nulla maximus, nisi vitae egestas ornare, sem leo feugiat augue, ut tristique magna odio ut mauris. Ut finibus massa ut ex luctus, at commodo turpis efficitur. Maecenas vestibulum est ac lobortis vehicula. Curabitur sit amet pellentesque turpis. Integer rhoncus eget urna vel mollis. Morbi quis orci accumsan, fermentum augue in, condimentum lacus.
Pellentesque quis augue urna. In facilisis, est sollicitudin feugiat suscipit, dui ipsum ullamcorper mauris, sed ultrices ligula mauris ut urna. Maecenas posuere varius consectetur. Nunc sed egestas metus, eu imperdiet neque. Suspendisse sit amet urna et dui rhoncus vestibulum sit amet facilisis eros. Cras molestie euismod nisl, sit amet vehicula tortor efficitur egestas. Nullam ac facilisis urna. Nunc tempor felis sed ipsum feugiat hendrerit. Vestibulum sed lobortis nisi. Proin laoreet tempus tempor. Ut sed hendrerit ante, sed interdum urna. Aliquam tempus eros vitae dictum vehicula. Vestibulum purus quam, elementum sit amet rutrum in, dapibus nec metus. Quisque in mollis dui. Sed malesuada posuere sem ac gravida.</div>
Unfortunately, Stackoverflow disables code snippets on poorly misjudged and underappreciated answers, so here is a jsfiddle link to run the code instead.
Try scrolling down through the page in the demo and observing how the background color changes as you scroll. Try using your cursor to move the scrollbar up and down rapidly to see if you can get it to break and fail to update the colors. It will not break because this is a sturdy solid throttling function. Once you find a color that you like, click the "Remove the scroll listener" button in order to stop changing colors.
Although changing the background color with scrolling is a bit impractical (on a real website, it would simply distract the user from the content), I hope that this demonstration serves to show how powerful a good throttle function can be in terms of performance and fluid user experience.
Comparison To Lodash
Observe the following Lodash implementation of a throttled function.
/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/** Used as references for various `Number` constants. */
var NAN = 0 / 0;
/** `Object#toString` result references. */
var symbolTag = '[object Symbol]';
/** Used to match leading and trailing whitespace. */
var reTrim = /^\s+|\s+$/g;
/** Used to detect bad signed hexadecimal string values. */
var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
/** Used to detect binary string values. */
var reIsBinary = /^0b[01]+$/i;
/** Used to detect octal string values. */
var reIsOctal = /^0o[0-7]+$/i;
/** Built-in method references without a dependency on `root`. */
var freeParseInt = parseInt;
/** Detect free variable `global` from Node.js. */
var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
/** Detect free variable `self`. */
var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
/** Used as a reference to the global object. */
var root = freeGlobal || freeSelf || Function('return this')();
/** Used for built-in method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the
//// Continued at https://cdn.jsdelivr.net/npm/lodash.throttle#4.1.1/index.js /////
Granted, the reason for why it is so big is because of all of the comments. Thus, let us compare the minified sizes:
// Lodash implementation: 1805 bytes (+GZip => 872 bytes);
// 19 suspended variables per throttle
throttle=function(){function A(a,b,c){function d(b){var p=g,c=k;g=k=void 0;l=b;return m=a.apply(c,p)}function h(a){var p=a-f;a-=l;return void 0===f||p>=b||0>p||q&&a>=u}function r(){var a=v.Date.now();if(h(a))return n(a);var c=setTimeout;var d=a-l;a=b-(a-f);d=q?B(a,u-d):a;e=c(r,d)}function n(a){e=void 0;if(w&&g)return d(a);g=k=void 0;return m}function x(){var a=v.Date.now(),c=h(a);g=arguments;k=this;f=a;if(c){if(void 0===e)return l=a=f,e=setTimeout(r,b),y?d(a):m;if(q)return e=setTimeout(r,b),d(f)}void 0===
e&&(e=setTimeout(r,b));return m}var g,k,m,e,f,l=0,y=!1,q=!1,w=!0;if("function"!=typeof a)throw new TypeError("Expected a function");b=z(b)||0;if(t(c)){y=!!c.leading;var u=(q="maxWait"in c)?C(z(c.maxWait)||0,b):u;w="trailing"in c?!!c.trailing:w}x.cancel=function(){void 0!==e&&clearTimeout(e);l=0;g=f=k=e=void 0};x.flush=function(){return void 0===e?m:n(v.Date.now())};return x}function t(a){var b=typeof a;return!!a&&("object"==b||"function"==b)}function z(a){if("number"==typeof a)return a;var b=a;if("symbol"==
typeof b||b&&"object"==typeof b&&"[object Symbol]"==D.call(b))return n;t(a)&&(a="function"==typeof a.valueOf?a.valueOf():a,a=t(a)?a+"":a);if("string"!=typeof a)return 0===a?a:+a;a=a.replace(E,"");return(b=F.test(a))||G.test(a)?H(a.slice(2),b?2:8):I.test(a)?n:+a}var n=0/0,E=/^\s+|\s+$/g,I=/^[-+]0x[0-9a-f]+$/i,F=/^0b[01]+$/i,G=/^0o[0-7]+$/i,H=parseInt,J="object"==typeof self&&self&&self.Object===Object&&self,v="object"==typeof global&&global&&global.Object===Object&&global||J||Function("return this")(),
D=Object.prototype.toString,C=Math.max,B=Math.min;return function(a,b,c){var d=!0,h=!0;if("function"!=typeof a)throw new TypeError("Expected a function");t(c)&&(d="leading"in c?!!c.leading:d,h="trailing"in c?!!c.trailing:h);return A(a,b,{leading:d,maxWait:b,trailing:h})}}()
But, what if we took all of that functionality in Lodash, stripped out the .cancel method (replacing it with mute/listen), made the leading options no longer an option, instead always true, and removed all of the fuss over typecasting under the assumption that you are conscious of which types you are using? The result is a radically debloated, much more performance, and just as useable throttling function that is my solution. Further, if you have special needs for a throttling function, then my solution is easily extendable with an optional 2nd parameter that defines a function to be called when an invocation to the main throttled function is dropped due to throttling.
// My implementation: 170 bytes (+GZip => 143 bytes);
// 5 suspended variables per throttle
function throttle(d,e,f){var c=!0,a=null;return function(b){if(c)return c=!1,setTimeout(function(b){c=!0;null!==a&&d(a);a=null},f),d(b);a=b;"function"===typeof e&&e(b)}};
The listen/mute are extra convenience methods that keep track of the throttle reference for you so that you do not have to. The minified Lodash code does not include these extra convenience, so why should my code have to be compared with conveniences to Lodash which is without conveniences? Thus, my above code snippet only represents my throttler without the listen/mute convenience methods.
Thus, I rest my case that my implementation is comparable to Lodash in functionality and far superior to Lodash in size and performa

Categories

Resources