Testando setInterval vs setTimeout

by jeffque

HTML

Advindo desta publicação: <a href='https://computaria.gitlab.io/blog/2024/05/19/pipeline-visible'>Deixando a pipeline visível para acompanhar deploy do blog</a>

<hr>

<script>
{
    // arrow functions não escapam escopo, porque são variáveis
    const sanitizeText = text => text ?? "";
    const findGarbagePlace = () => document.getElementById("garbage-place");

    const appendGarbagePlace = (text) => {
        const gp = findGarbagePlace();
        gp.value += sanitizeText(text);
    }

    let aboboraId = null;

    // functions escapam escopo
    function iniciaTimeout() {
        if (aboboraId) {
            paraTimeout()
        }
        clearGarbagePlace();
        const stepAppendAbobora = (cntDown, timeout) => {
            aboboraId = setTimeout(() => {
                if (cntDown == 0) {
                    aboboraId = null; // limpando
                    return;
                }
                appendGarbagePlace(`abobora ${cntDown}\n`)
                stepAppendAbobora(cntDown - 1, timeout)
            }, timeout);
        }

        stepAppendAbobora(5, 200)
    }

    function paraTimeout() {
        if (aboboraId) {
            clearTimeout(aboboraId);
            aboboraId = null; // limpando
        }
    }

    function clearGarbagePlace() {
        const gp = findGarbagePlace();
        gp.value = "";
    }
}
</script>

<button onClick="iniciaTimeout()">Inicia timeout</button>
<button onClick="paraTimeout()">Para timeout</button>
<button onClick="clearGarbagePlace()">Limpa o place abaixo</button>
<textarea id="garbage-place" disabled="true" cols="80" rows="6" placeholder="(ainda sem valor...)">
</textarea>

<hr>


<script>
{
    // arrow functions não escapam escopo, porque são variáveis
    const sanitizeText = text => text ?? "";
    const findGarbagePlace = () => document.getElementById("garbage-place2");

    const appendGarbagePlace = (text) => {
        const gp = findGarbagePlace();
        gp.value += sanitizeText(text);
    }

   ...