Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

218
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!