Skip to content

Scheduling: setTimeout and setInterval - #483

Open
diogoosz wants to merge 1 commit into
javascript-tutorial:masterfrom
diogoosz:translate-settimeout-setinterval
Open

diogoosz wants to merge 1 commit into
javascript-tutorial:masterfrom
diogoosz:translate-settimeout-setinterval

Conversation

@diogoosz

@diogoosz diogoosz commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Tradução do artigo "Scheduling: setTimeout and setInterval" para o português, incluindo os exercícios.

Conforme comentado na #1.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
- O navegador limita o atraso mínimo para cinco ou mais chamadas aninhadas de `setTimeout` ou para `setInterval` (depois da 5ª chamada) a 4ms. Isso é por motivos históricos.

Please note that all scheduling methods do not *guarantee* the exact delay.
Observe que todos os métodos de agendamento não *garantem* o atraso exato.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Calque of "all ... do not guarantee": in Portuguese "todos ... não garantem" reads as "not all guarantee" (some might). The intended meaning is that none guarantee it.

Suggested change
Observe que todos os métodos de agendamento não *garantem* o atraso exato.
Observe que nenhum método de agendamento *garante* o atraso exato.

Existe um caso de uso especial: `setTimeout(func, 0)`, ou simplesmente `setTimeout(func)`.

This schedules the execution of `func` as soon as possible. But the scheduler will invoke it only after the currently executing script is complete.
Isso agenda a execução de `func` o quanto antes possível. Mas o agendador só vai chamá-la depois que o script em execução no momento terminar.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"o quanto antes possível" mixes two idioms ("o quanto antes" / "o mais cedo possível") and is ungrammatical. Same at line 292.

Suggested change
Isso agenda a execução de `func` o quanto antes possível. Mas o agendador só vai chamá-la depois que o script em execução no momento terminar.
Isso agenda a execução de `func` o mais cedo possível. Mas o agendador só vai chamá-la depois que o script em execução no momento terminar.

- Os métodos `setTimeout(func, delay, ...args)` e `setInterval(func, delay, ...args)` nos permitem rodar `func` uma vez/regularmente depois de `delay` milissegundos.
- Para cancelar a execução, devemos chamar `clearTimeout/clearInterval` com o valor retornado por `setTimeout/setInterval`.
- Chamadas de `setTimeout` aninhadas são uma alternativa mais flexível ao `setInterval`, nos permitindo definir o tempo *entre* as execuções com mais precisão.
- Agendamento com atraso zero usando `setTimeout(func, 0)` (o mesmo que `setTimeout(func)`) é usado para agendar a chamada "o quanto antes possível, mas depois que o script atual terminar".

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same "o quanto antes possível" issue as line 242.

Suggested change
- Agendamento com atraso zero usando `setTimeout(func, 0)` (o mesmo que `setTimeout(func)`) é usado para agendar a chamada "o quanto antes possível, mas depois que o script atual terminar".
- Agendamento com atraso zero usando `setTimeout(func, 0)` (o mesmo que `setTimeout(func)`) é usado para agendar a chamada "o mais cedo possível, mas depois que o script atual terminar".

No navegador, existe uma limitação de com que frequência timers aninhados podem rodar. O [HTML Living Standard](https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html#timers) diz: "depois de cinco timers aninhados, o intervalo é forçado a ser de pelo menos 4 milissegundos.".

Let's demonstrate what it means with the example below. The `setTimeout` call in it re-schedules itself with zero delay. Each call remembers the real time from the previous one in the `times` array. What do the real delays look like? Let's see:
Vamos demonstrar o que isso significa com o exemplo abaixo. A chamada `setTimeout` nele reagenda a si mesma com atraso zero. Cada chamada lembra o tempo real desde a anterior no array `times`. Como são os atrasos reais? Vamos ver:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Text (and the code comment on line 268) say each call stores the time "desde a anterior", but the code pushes Date.now() - start, i.e. elapsed time since the start. The sample output 1,1,1,1,9,15,20,... is cumulative, which confirms it. The English original has the same mistake; the translation could fix it instead of carrying it over, e.g. "Cada chamada guarda no array times o tempo real decorrido desde o início." and "// guarda o tempo decorrido desde o início".

A primeira linha "coloca a chamada no calendário depois de 0ms". Mas o agendador só vai "checar o calendário" depois que o script atual terminar, então `"Hello"` vem primeiro, e `"World"` -- depois dele.

There are also advanced browser-related use cases of zero-delay timeout, that we'll discuss in the chapter <info:event-loop>.
Também existem casos de uso mais avançados, relacionados a navegadores, de atraso zero, que vamos discutir no capítulo <info:event-loop>.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The original says "use cases of zero-delay timeout". Without "timeout" the phrase "casos de uso ... de atraso zero" no longer says what has zero delay.

Suggested change
Também existem casos de uso mais avançados, relacionados a navegadores, de atraso zero, que vamos discutir no capítulo <info:event-loop>.
Também existem casos de uso avançados do `setTimeout` com atraso zero, relacionados a navegadores, que vamos discutir no capítulo <info:event-loop>.

Observe que, nas duas soluções, há um atraso inicial antes da primeira exibição. A função é chamada pela primeira vez depois de `1000ms`.

If we also want the function to run immediately, then we can add an additional call on a separate line, like this:
Se também quisermos que a função rode imediatamente, podemos adicionar uma chamada extra numa linha separada, assim:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not introduced by this PR, but this file is touched: in the third solution below, go() (line 58) runs before let timerId = setInterval(go, 1000). When from == to (e.g. printNumbers(5, 5)), go() reaches clearInterval(timerId) while timerId is still in the TDZ, so it throws ReferenceError: Cannot access timerId before initialization. Consider declaring let timerId; before calling go(), or report it upstream.

setTimeout(() => alert(i), 100); // ?

// assume that the time to execute this function is >100ms
// assuma que o tempo para executar essa função é >100ms

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment says "essa função", but what follows is a for loop, not a function. The English original has the same slip ("this function"); "este laço" is clearer and matches the task text ("Depois do laço"). The same comment appears in solution.md:11.

Suggested change
// assuma que o tempo para executar essa função é >100ms
// assuma que o tempo para executar este laço é >100ms

setTimeout(() => alert(i), 100); // 100000000

// assume that the time to execute this function is >100ms
// assuma que o tempo para executar essa função é >100ms

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as task.md:23. This is a loop, not a function.

Suggested change
// assuma que o tempo para executar essa função é >100ms
// assuma que o tempo para executar este laço é >100ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants