javascript-tutorial / javascript-tutorial/en.javascript.info
Solution for throttle decorator is incorrect. (Decorators and forwarding, call/apply)
還沒有人認領這個 Issue。
- 主要語言
- HTML
- 星號
- 25.5k
- 分支
- 4k
- PR 合併指標
- 30 天內沒有已合併 PR
描述
Original code: https://javascript.info/call-apply-decorators#throttle-decorator
Here's a small code snippet to show where it doesn't work.
```js
function f(a) { console.log(a) };
let g = throttle(f, 1000);
for(let i = 0; i < 1e8; i++) g(i);
```
#### Expected Output
1, 249204, 452039, ... , 9999999 (These are random increasing numbers)
#### Output
1, 9999999
#### Why does it fail?
```js
function wrapper() {
if (isThrottled) { // (2)
savedArgs = arguments;
savedThis = this;
return;
}
isThrottled = true;
func.apply(this, arguments); // (1)
setTimeout(function() {
isThrottled = false; // (3)
if (savedArgs) {
wrapper.apply(savedThis, savedArgs);
savedArgs = savedThis = null;
}
}, ms);
}
```
In above, `isThrottled = false` assignment is done inside `setTimeout` callback. However, only one callback is pushed into task queue and it isn't executed until stack is empty (for loop has to be completed).
`isThrottled` is always `true` => `setTimeout` isn't called => one callback (that was registered for initial false `isThrottled`) => cb executed at end and outputs last value => output: 1, 9999999.
#### Correct Solution: https://github.com/javascript-tutorial/en.javascript.info/pull/2844
This PR giving an alternative solution.
貢獻指南
這個儲存庫沒有索引到貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從連結的教學「Decorators and forwarding, call/apply」部分中的 throttle decorator 範例開始,並重現所提供的 tight-loop snippet。將目前行為與 pull request #2844 進行比較;完成的標準是該範例不再將迴圈壓縮為只有第一個值和最後一個值。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- javascript
- 領域
- documentation
- Issue 類型
- 缺陷
- 難度
- 2/5
- 預估耗時
- 1-3 小時
- 活躍度
- 停滯
- 描述清晰度
- 描述清楚
- 新手友好度
- 35/100