javascript-tutorial / javascript-tutorial/en.javascript.info
Solution for throttle decorator is incorrect. (Decorators and forwarding, call/apply)
Chưa có ai nhận issue này.
- Ngôn ngữ chính
- HTML
- Star
- 25.5k
- Fork
- 4k
- Chỉ số merge pull request
- Không có pull request nào được merge trong 30 ngày
Mô tả
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.
Hướng dẫn đóng góp
Chưa lập chỉ mục được hướng dẫn đóng góp cho kho mã nguồn này
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Hướng nghiên cứu
Bắt đầu với ví dụ về throttle decorator trong phần tutorial được liên kết «Decorators and forwarding, call/apply» và tái hiện snippet tight loop đã cung cấp. So sánh hành vi hiện tại với pull request #2844; được xem là hoàn tất khi ví dụ không còn rút gọn loop chỉ còn các giá trị đầu tiên và cuối cùng.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Đánh giá
- Công nghệ
- javascript
- Lĩnh vực
- documentation
- Loại issue
- Lỗi
- Độ khó
- 2/5
- Thời gian dự kiến
- 1-3 giờ
- Mức độ hoạt động
- Đình trệ
- Độ rõ ràng
- Đặc tả rõ ràng
- Mức phù hợp với người mới
- 35/100