You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: 1-js/06-advanced-functions/09-call-apply-decorators/02-delay/solution.md
+7-7Lines changed: 7 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,4 +1,4 @@
1
-
The solution:
1
+
Рішення:
2
2
3
3
```js run demo
4
4
functiondelay(f, ms) {
@@ -11,22 +11,22 @@ function delay(f, ms) {
11
11
12
12
let f1000 =delay(alert, 1000);
13
13
14
-
f1000("test"); //shows "test" after 1000ms
14
+
f1000("тест"); //показує "тест" після 1000 мс
15
15
```
16
16
17
-
Please note how an arrow function is used here. As we know, arrow functions do not have own `this`and`arguments`, so`f.apply(this, arguments)`takes`this`and`arguments`from the wrapper.
17
+
Зверніть увагу, як тут використовується стрілочна функція. Як відомо, стрілочні функції не мають власних `this`та`arguments`, тому`f.apply(this, arguments)`бере`this`та`arguments`з обгортки.
18
18
19
-
If we pass a regular function, `setTimeout`would call it without arguments and`this=window` (assuming we're in the browser).
19
+
Якщо ми передамо звичайну функцію, `setTimeout`буде викликати її без аргументів, а`this=window` (припускаючи, що ми знаходимося в браузері).
20
20
21
-
We still can pass the right`this`by using an intermediate variable, but that's a little bit more cumbersome:
21
+
Ми все ще можемо передати право`this`за допомогою проміжної змінної, але це трохи більше громіздко:
22
22
23
23
```js
24
24
functiondelay(f, ms) {
25
25
26
26
returnfunction(...args) {
27
-
let savedThis =this; //store this into an intermediate variable
27
+
let savedThis =this; //зберігаємо this в проміжну змінну
Copy file name to clipboardExpand all lines: 1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/solution.md
+1-1Lines changed: 1 addition & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -9,5 +9,5 @@ function debounce(func, ms) {
9
9
10
10
```
11
11
12
-
A call to `debounce`returns a wrapper. When called, it schedules the original function call after given `ms`and cancels the previous such timeout.
12
+
Виклик `debounce`повертає обгортку. Коли він викликається, він відкладає виклик оригінальної функції після даного `ms`і скасовує попередній подібний тайм-аут.
Copy file name to clipboardExpand all lines: 1-js/06-advanced-functions/09-call-apply-decorators/03-debounce/task.md
+17-17Lines changed: 17 additions & 17 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -2,50 +2,50 @@ importance: 5
2
2
3
3
---
4
4
5
-
# Debounce decorator
5
+
# Декоратор debounce
6
6
7
-
The result of `debounce(f, ms)`decorator is a wrapper that suspends calls to`f` until there's `ms`milliseconds of inactivity (no calls, "cooldown period"), then invokes `f`once with the latest arguments.
7
+
Результат `debounce(f, ms)`декоратору -- це обгортка, що призупиняє виклики до`f`, поки не пройде `ms`мілісекунд бездіяльності (без викликів, "cooldown period"), а потім викликає `f`один раз з останніми аргументами.
8
8
9
-
In other words, `debounce`is like a secretary that accepts "phone calls", and waits until there's `ms`milliseconds of being quiet. And only then it transfers the latest call information to "the boss" (calls the actual`f`).
9
+
Іншими словами, `debounce`-- це як секретар, який приймає "телефонні дзвінки", і чекає, поки не закінчаться `ms`мілісекунди тиші. І лише тоді він передає останню інформацію про виклик до "боса" (викликає фактичну`f`).
10
10
11
-
For instance, we had a function`f`and replaced it with`f = debounce(f, 1000)`.
11
+
Наприклад, у нас була функція`f`і замінили її на`f = debounce(f, 1000)`.
12
12
13
-
Then if the wrapped function is called at 0ms, 200ms and 500ms, and then there are no calls, then the actual `f`will be only called once, at 1500ms. That is: after the cooldown period of 1000ms from the last call.
13
+
Тоді, якщо загорнута функція викликається при 0 мс, 200 мс та 500 мс, а потім викликів немає, то фактична `f`буде викликатися лише один раз, при 1500 мс. Тобто: після закінчення періоду 1000 мс від останнього виклику.
14
14
15
15

16
16
17
-
...And it will get the arguments of the very last call, other calls are ignored.
17
+
...І вона отримає аргументи самого останнього виклику, а інші виклики будуть ігноруватися.
18
18
19
-
Here's the code for it (uses the debounce decorator from the[Lodash library](https://lodash.com/docs/4.17.15#debounce)):
19
+
Ось код для цього (використовує декоратор debounce з[Lodash library](https://lodash.com/docs/4.17.15#debounce)):
20
20
21
21
```js
22
22
let f =_.debounce(alert, 1000);
23
23
24
24
f("a");
25
25
setTimeout( () =>f("b"), 200);
26
26
setTimeout( () =>f("c"), 500);
27
-
// debounced function waits 1000ms after the last call and then runs: alert("c")
27
+
//повернута з debounced функція чекає 1000 мс після останнього виклику, а потім запускає: alert("c")
28
28
```
29
29
30
-
Now a practical example. Let's say, the user types something, and we'd like to send a request to the server when the input is finished.
30
+
Тепер практичний приклад. Скажімо, користувач друкує щось, і ми хотіли б надіслати запит на сервер, коли ввід закінчиться.
31
31
32
-
There's no point in sending the request for every character typed. Instead we'd like to wait, and then process the whole result.
32
+
Немає сенсу надсилати запит на кожен набраний символ. Замість цього ми хотіли б почекати, а потім обробляти весь результат.
33
33
34
-
In a web-browser, we can setup an event handler -- a function that's called on every change of an input field. Normally, an event handler is called very often, for every typed key. But if we `debounce`it by 1000ms, then it will be only called once, after 1000ms after the last input.
34
+
У веббраузері ми можемо налаштувати обробник подій -- функцію, яка викликається при кожній зміні поля введення.Зазвичай, обробник подій викликається дуже часто, для кожного друкованого символу. Але якщо ми використаємо `debounce`на 1000 мс, то він буде викликатися лише один раз, через 1000 мс після останнього введення.
35
35
36
36
```online
37
37
38
-
In this live example, the handler puts the result into a box below, try it:
38
+
У цьому реальному прикладі обробник ставить результат у поле нижче, спробуйте це:
39
39
40
40
[iframe border=1 src="debounce" height=200]
41
41
42
-
See? The second input calls the debounced function, so its content is processed after 1000ms from the last input.
42
+
Бачите? Другий ввід викликає функцію, що була повернута з `debounce`, тому цей вміст обробляється через 1000 мс з останнього введення.
43
43
```
44
44
45
-
So, `debounce`is a great way to process a sequence of events: be it a sequence of key presses, mouse movements or something else.
45
+
Отже, `debounce`-- це чудовий спосіб обробки послідовності подій: будь то послідовність натискання клавіш, рухів миші або щось інше.
46
46
47
-
It waits the given time after the last call, and then runs its function, that can process the result.
47
+
Він чекає певного часу після останнього дзвінка, а потім запускає свою функцію, яка може обробити результат.
48
48
49
-
The task is to implement `debounce` decorator.
49
+
Завдання полягає в тому, щоб реалізувати декоратор `debounce`.
50
50
51
-
Hint: that's just a few lines if you think about it :)
51
+
Підказка: Це лише кілька рядків, якщо ви думаєте про це :)
0 commit comments