Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
Inbuilt function clearInterval is not working Javascript

I am learning setTimeout, setInterval, clearInterval functions.

now I tried to write such code, but clearInterval is not working. Code:

<h2>Hello!</h2>
<p>i am a paragraph</p>
<button onclick="setInterval(messageOnInterval, 110)">Click Me</button>
<button onclick="clearInterval(messageOnInterval)">Stop</button>
<script>
    function messageOnInterval() {
        
        var p=document.createElement('p');
            p.innerHTML = "i am a paragraph";
            document.body.appendChild(p);
        
    }
</script>

Thank you in advance for help!

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

setInterval returns a value that needs to be used when calling clearInterval. You don't pass the function as arg, but the value returned by an earlier call to setInterval

id = setInterval(messageOnInterval, 110)
clearInterval(id)

In your case you should declare a JS variable inside a script and use that as your id.

Note: this will not properly work if you press the button multiple times, as you'll lose older setInteval returned values.

about 4 years ago · Juan Pablo Isaza Relatório

0

You should assign setInterval to a variable to get it's handle which is in number format, then you can call clearInterval to clear that timer.

You cannot assign a function to clearInterval.

So it should be like this:

<script>
    function messageOnInterval_Impl() {
        var p = document.createElement('p');
        p.innerHTML = "i am a paragraph";
        document.body.appendChild(p);

    }

    var intervalHandle;
    function setMessageOnInterval() {
        intervalHandle = setInterval(function () {
            messageOnInterval_Impl();
            // ... 
        }, 110)
    }
</script>

<h2>Hello!</h2>
<p>i am a paragraph</p>
<button onclick="setMessageOnInterval()">Click Me</button>
<button onclick="clearInterval(intervalHandle)">Stop</button>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda