Skip to content

Commit 151cc2b

Browse files
committed
03-debounce
1 parent c9a1058 commit 151cc2b

3 files changed

Lines changed: 25 additions & 27 deletions

File tree

1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/_js.view/test.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ describe("debounce", function() {
77
this.clock.restore();
88
});
99

10-
it("calls the function at maximum once in ms milliseconds", function() {
10+
it("вызывает функцию максимум один раз в мс", function() {
1111
let log = '';
1212

1313
function f(a) {
@@ -16,18 +16,18 @@ describe("debounce", function() {
1616

1717
f = debounce(f, 1000);
1818

19-
f(1); // runs at once
20-
f(2); // ignored
19+
f(1); // вызвана
20+
f(2); // проигнорирована
2121

22-
setTimeout(() => f(3), 100); // ignored (too early)
23-
setTimeout(() => f(4), 1100); // runs (1000 ms passed)
24-
setTimeout(() => f(5), 1500); // ignored (less than 1000 ms from the last run)
22+
setTimeout(() => f(3), 100); // проигнорирована (слишком рано)
23+
setTimeout(() => f(4), 1100); // вызвана (1000 мс истекли)
24+
setTimeout(() => f(5), 1500); // проигнорирована (менее 1000 мс с последнего вызова)
2525

2626
this.clock.tick(5000);
2727
assert.equal(log, "14");
2828
});
2929

30-
it("keeps the context of the call", function() {
30+
it("сохраняет контекст вызова", function() {
3131
let obj = {
3232
f() {
3333
assert.equal(this, obj);
@@ -38,4 +38,4 @@ describe("debounce", function() {
3838
obj.f("test");
3939
});
4040

41-
});
41+
});

1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/solution.md

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,12 @@ function debounce(f, ms) {
1616
}
1717
```
1818

19-
A call to `debounce` returns a wrapper. There may be two states:
19+
Вызов `debounce` возвращает обёртку. Возможны два состояния:
20+
- `isCooldown = false` -- готова к выполнению.
21+
- `isCooldown = true` -- ожидание окончания тайм-аута.
2022

21-
- `isCooldown = false` -- ready to run.
22-
- `isCooldown = true` -- waiting for the timeout.
23+
В первом вызове `isCoolDown` является ложным, поэтому вызов продолжается, и состояние изменяется на `true`.
2324

24-
In the first call `isCooldown` is falsy, so the call proceeds, and the state changes to `true`.
25+
Пока `isCoolDown` имеет значение true, все остальные вызовы игнорируются.
2526

26-
While `isCooldown` is true, all other calls are ignored.
27-
28-
Then `setTimeout` reverts it to `false` after the given delay.
27+
Затем `setTimeout` устанавливает в него значение `false` после заданной задержки.
Lines changed: 11 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,23 @@
1-
importance: 5
1+
важность: 5
22

33
---
44

5-
# Debounce decorator
5+
# Отклоняющий декоратор
66

7-
The result of `debounce(f, ms)` decorator should be a wrapper that passes the call to `f` at maximum once per `ms` milliseconds.
7+
Результатом декоратора `debounce(f, ms)` должна быть обёртка, которая передает вызов `f` не более одного раза в `ms` миллисекунд.
8+
Другими словами, когда мы вызываем «отклоненную» функцию, это гарантирует, что все остальные вызовы будут игнорироваться в течении `ms`.
89

9-
In other words, when we call a "debounced" function, it guarantees that all other future in the closest `ms` milliseconds will be ignored.
10-
11-
For instance:
10+
Например:
1211

1312
```js no-beautify
1413
let f = debounce(alert, 1000);
1514

16-
f(1); // runs immediately
17-
f(2); // ignored
15+
f(1); // выполняется немедленно
16+
f(2); // проигнорирован
1817

19-
setTimeout( () => f(3), 100); // ignored ( only 100 ms passed )
20-
setTimeout( () => f(4), 1100); // runs
21-
setTimeout( () => f(5), 1500); // ignored (less than 1000 ms from the last run)
18+
setTimeout( () => f(3), 100); // проигнорирован ( прошло только 100 мс )
19+
setTimeout( () => f(4), 1100); // выполняется
20+
setTimeout( () => f(5), 1500); // проигнорирован ( прошло только 100 мс от последнего вызова)
2221
```
2322

24-
In practice `debounce` is useful for functions that retrieve/update something when we know that nothing new can be done in such a short period of time, so it's better not to waste resources.
23+
На практике `debounce` полезен для функций, которые извлекают/обновляют что-то и мы знаем, что ничего нового нельзя сделать за такой короткий период времени, поэтому лучше не тратить ресурсы.

0 commit comments

Comments
 (0)