Throttle function won't run without interval constant
class Neuron {
fire() {
console.log("Firing!");
}
Function.prototype.myThrottle = function(interval) {
// declare a variable outside of the returned function
let tooSoon = false;
return (...args) => {
// the function only gets invoked if tooSoon is false
// it sets tooSoon to true, and uses setTimeout to set it back to
// false after interval ms
// any invocation within this interval will skip the if
// statement and do nothing
if (!tooSoon) {
tooSoon = true;
setTimeout(() => tooSoon = false, interval);
this(...args); // confused what this piece of code does.
}
}
function printFire(){ return neuron.fire()}
const neuron = new Neuron();
neuron.fire = neuron.fire.myThrottle(500);
const interval = setInterval(printFire, 10);
This piece of code will output "Firing!, once every 500ms". My confusion is when I comment "const interval = setInterval(printFire, 10) ", The code does not run at all. I feel const interval should not get called if we already have neuron.fire = ...myThrottle(500). I'm just confused on the sequence of events in this piece of code. Also the line "this(...args)" is calling a function but not sure what exactly.
Very knew javascript is so all responses will be greatly appreciated. thank you!
from Recent Questions - Stack Overflow https://ift.tt/3fUzDbK
https://ift.tt/eA8V8J
Comments
Post a Comment