|
24 | 24 | new Foo();
|
25 | 25 |
|
26 | 26 |
|
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` вообще **не** породит никакой ошибки. |
32 | 28 |
|
33 |
| -### Stacking calls with `setInterval` |
| 29 | +### Поочерёдные вызовы с использованием `setInterval` |
34 | 30 |
|
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` миллисекунд. И его использование не рекомендуется. |
38 | 32 |
|
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` будет продолжать планировать последующие вызовы переданной функции. Это может, особенно в случае небольших интервалов, повлечь за собой выстраивание вызовов функций в очередь. |
42 | 34 |
|
43 | 35 | function foo(){
|
44 |
| - // something that blocks for 1 second |
| 36 | + // что-то, что выполняется одну секунду |
45 | 37 | }
|
46 | 38 | setInterval(foo, 100);
|
47 | 39 |
|
48 |
| -In the above code `foo` will get called once and will then block for one second. |
| 40 | +В приведённом коде `foo` выполнится один раз и заблокирует этим главный поток на одну секунду. |
49 | 41 |
|
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`. |
53 | 43 |
|
54 |
| -### Dealing with possible blocking code |
| 44 | +### Разбираемся с потенциальной блокировкой кода |
55 | 45 |
|
56 |
| -The easiest as well as most controllable solution, is to use `setTimeout` within |
57 |
| -the function itself. |
| 46 | +Самый простой и контролируемый способ — использовать `setTimeout` внутри самой функции. |
58 | 47 |
|
59 | 48 | function foo(){
|
60 |
| - // something that blocks for 1 second |
| 49 | + // что-то, выполняющееся одну секунду |
61 | 50 | setTimeout(foo, 100);
|
62 | 51 | }
|
63 | 52 | foo();
|
64 | 53 |
|
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` теперь принимает решение, хочет ли она запускаться ещё раз или нет. |
68 | 55 |
|
69 |
| -### Manually clearing timeouts |
| 56 | +### Очистка таймаутов вручную |
70 | 57 |
|
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...` использовалась для его получения. |
74 | 59 |
|
75 | 60 | var id = setTimeout(foo, 1000);
|
76 | 61 | clearTimeout(id);
|
77 | 62 |
|
78 |
| -### Clearing all timeouts |
| 63 | +### Очистка всех таймаутов |
79 | 64 |
|
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 | +Из-за того, что встроенного метода для удаления всех таймаутов и/или интервалов не существует, для достижения этой цели приходится использовать брутфорс. |
82 | 66 |
|
83 |
| - // clear "all" timeouts |
| 67 | + // удаляем "все" таймауты |
84 | 68 | for(var i = 1; i < 1000; i++) {
|
85 | 69 | clearTimeout(i);
|
86 | 70 | }
|
87 | 71 |
|
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 | +Вполне могут остаться таймауты, которые не будут захвачены этим произвольным числом; так что рекомендуется следить за идентификаторами всех создающихся таймаутов, засчёт чего их можно будет удалять индивидуально. |
91 | 73 |
|
92 |
| -### Hidden use of `eval` |
| 74 | +### Скрытое использование `eval` |
93 | 75 |
|
94 | 76 | `setTimeout` and `setInterval` can also take a string as their first parameter.
|
95 | 77 | 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.
|
142 | 124 | Further, the use of `setInterval` should be avoided since its scheduler is not
|
143 | 125 | blocked by executing JavaScript.
|
144 | 126 |
|
145 |
| -[1]: http://en.wikipedia.org/wiki/Document_Object_Model |
| 127 | +[1]: http://ru.wikipedia.org/wiki/Document_Object_Model |
146 | 128 |
|
0 commit comments