Skip to content

Commit ea30e5e

Browse files
committed
other/timeouts, part 2
1 parent b4bd690 commit ea30e5e

File tree

1 file changed

+19
-37
lines changed

1 file changed

+19
-37
lines changed

doc/ru/other/timeouts.md

Lines changed: 19 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -24,72 +24,54 @@
2424
new Foo();
2525

2626

27-
> **Note:** As `setTimeout` takes a **function object** as its first parameter, an
28-
> often made mistake is to use `setTimeout(foo(), 1000)`, which will use the
29-
> **return value** of the call `foo` and **not** `foo`. This is, most of the time,
30-
> a silent error, since when the function returns `undefined` `setTimeout` will
31-
> **not** raise any error.
27+
> **Замечание:** Поскольку `setTimeout` принимает **объект функции** в качестве первого параметра часто совершается ошибка в использовании `setTimeout(foo(), 1000)`, при котором будет использоваться **возвращённое значение** от вызова `foo`, а **не** вызвана функция `foo`. В большинстве случаев ошибка пройдёт незамеченной, а в случае если функция возвращает `undefined`, `setTimeout` вообще **не** породит никакой ошибки.
3228
33-
### Stacking calls with `setInterval`
29+
### Поочерёдные вызовы с использованием `setInterval`
3430

35-
While `setTimeout` only runs the function once, `setInterval` - as the name
36-
suggests - will execute the function **every** `X` milliseconds. But its use is
37-
discouraged.
31+
`setTimeout` вызывает функцию единожды; `setInterval` — как и предполагает название — вызывает функцию **каждые** `X` миллисекунд. И его использование не рекомендуется.
3832

39-
When code that is being executed blocks the timeout call, `setInterval` will
40-
still issue more calls to the specified function. This can, especially with small
41-
intervals, result in function calls stacking up.
33+
В то время, когда исполняющийся код будет блокироваться во время вызова с таймаутом, `setInterval` будет продолжать планировать последующие вызовы переданной функции. Это может, особенно в случае небольших интервалов, повлечь за собой выстраивание вызовов функций в очередь.
4234

4335
function foo(){
44-
// something that blocks for 1 second
36+
// что-то, что выполняется одну секунду
4537
}
4638
setInterval(foo, 100);
4739

48-
In the above code `foo` will get called once and will then block for one second.
40+
В приведённом коде `foo` выполнится один раз и заблокирует этим главный поток на одну секунду.
4941

50-
While `foo` blocks the code `setInterval` will still schedule further calls to
51-
it. Now, when `foo` has finished, there will already be **ten** further calls to
52-
it waiting for execution.
42+
Пока `foo` блокирует код, `setInterval` продолжает планировать последующие её вызовы. Теперь, когда первая `foo` закончила выполнение, в очереди будут уже **десять** ожидающих выполнения вызовов `foo`.
5343

54-
### Dealing with possible blocking code
44+
### Разбираемся с потенциальной блокировкой кода
5545

56-
The easiest as well as most controllable solution, is to use `setTimeout` within
57-
the function itself.
46+
Самый простой и контролируемый способ — использовать `setTimeout` внутри самой функции.
5847

5948
function foo(){
60-
// something that blocks for 1 second
49+
// что-то, выполняющееся одну секунду
6150
setTimeout(foo, 100);
6251
}
6352
foo();
6453

65-
Not only does this encapsulate the `setTimeout` call, but it also prevents the
66-
stacking of calls and it gives additional control.`foo` itself can now decide
67-
whether it wants to run again or not.
54+
Такой способ не только инкапсулирует вызов `setTimeout`, но и предотвращает от очередей блокирующих вызовов и обеспечивает дополнительный контроль. Сама функция `foo` теперь принимает решение, хочет ли она запускаться ещё раз или нет.
6855

69-
### Manually clearing timeouts
56+
### Очистка таймаутов вручную
7057

71-
Clearing timeouts and intervals works by passing the respective ID to
72-
`clearTimeout` or `clearInterval`, depending which `set` function was used in
73-
the first place.
58+
Удаление таймаутов и интервалов работает через передачу соответствуюего идентификатора либо в функцию `clearTimeout`, либо в функцию `clearInterval` — в зависимости от того, какая функция `set...` использовалась для его получения.
7459

7560
var id = setTimeout(foo, 1000);
7661
clearTimeout(id);
7762

78-
### Clearing all timeouts
63+
### Очистка всех таймаутов
7964

80-
As there is no built-in method for clearing all timeouts and/or intervals,
81-
it is necessary to use brute force in order to achieve this functionality.
65+
Из-за того, что встроенного метода для удаления всех таймаутов и/или интервалов не существует, для достижения этой цели приходится использовать брутфорс.
8266

83-
// clear "all" timeouts
67+
// удаляем "все" таймауты
8468
for(var i = 1; i < 1000; i++) {
8569
clearTimeout(i);
8670
}
8771

88-
There might still be timeouts that are unaffected by this arbitrary number;
89-
therefore, is is instead recommended to keep track of all the timeout IDs, so
90-
they can be cleared specifically.
72+
Вполне могут остаться таймауты, которые не будут захвачены этим произвольным числом; так что рекомендуется следить за идентификаторами всех создающихся таймаутов, засчёт чего их можно будет удалять индивидуально.
9173

92-
### Hidden use of `eval`
74+
### Скрытое использование `eval`
9375

9476
`setTimeout` and `setInterval` can also take a string as their first parameter.
9577
This feature should **never** be used, since it internally makes use of `eval`.
@@ -142,5 +124,5 @@ be passed that then takes care of the actual call.
142124
Further, the use of `setInterval` should be avoided since its scheduler is not
143125
blocked by executing JavaScript.
144126

145-
[1]: http://en.wikipedia.org/wiki/Document_Object_Model
127+
[1]: http://ru.wikipedia.org/wiki/Document_Object_Model
146128

0 commit comments

Comments
 (0)