// 📁 index.js
const { log } = console;
const { throttle } = require('./throttle.js');
// object
let user = {
// property
name: 'Joe',
// method
say(...args) {
const t = Date.now(); // current time
const T = (t - t0)/1000; // time elapsed in seconds
log(T.toFixed(2), `${this.name}: '${args}'`);
}
};
// passes calls to `user.say` at maximum once per 1000 ms
user.say = throttle(user.say, 1);
// send message
function send(msg, sec) {
setTimeout(() => user.say(msg), sec * 1000)
}
const t0 = Date.now();
send('a', 0.5);
send('b', 1.2);
send('c', 2);
send('d', 2.5);
send('e', 4);
send('d', 4.5);
// ✅ ✅ ❌ ✅ ✅ ✅
// a b d e f <---- forwarded calls
// |<──CDM──>| |<──CDM──>|
// |<──CDM──>| |<──CDM──>| |<──CDM──>|
// (a) [b] [c] [d] (e) [f]
// |....╷....|....╷....|....╷....|....╷....|....╷....|....╷....|
// 0 1 2 3 4 5 6 sec
//
// CDM: "cooldown" mode
// (a): send call (a)
// [b]: save call (b)
// d : forworded call
// log
// --------------------
// 'say' has been throttled by every 1 seconds.
//
// 0.50 Joe: 'a'
// 1.50 Joe: 'b'
// 2.50 Joe: 'd'
// 4.00 Joe: 'e'
// 5.00 Joe: 'd'