Search code examples
javascripttimercounterticker

converting string while making JavaScript Ticker


I want the counter(1, 2, 3, ....) started as soon as I click the Start button.

HTML code:

<p class="para">0</p>
<input type="button" value="Start" class="start">

JS code:

const para = document.querySelector(".para"),
      start = document.querySelector(".start");

start.addEventListener("click", function(){
      var timer = setInterval(doEverySecond, 1000)
      })

function doEverySecond(timer){
  parseInt(para++);
 }

I am stuck in this problem for three days. Please help me figure out my mistakes Do I need to use parseInt method because the para class is string not an integer? I hope I am clear


Solution

  • There are multiple things that may be causing you trouble here.

    1. You're not updating the paragraph's text, so you don't see any changes
    2. You set an interval with the window, so it should be window.setInterval()
    3. You don't need to assign a variable to your interval
    4. It's not a good idea to call ++ on a String

    When we fix these minor issues, everything works!

    const para = document.querySelector(".para"), start = document.querySelector(".start");
    
    start.addEventListener("click", function() {
      window.setInterval(doEverySecond, 1000)
    })
    
    function doEverySecond() {
      para.innerHTML = parseInt(para.innerHTML) + 1
    }
    <p class="para">0</p>
    <input type="button" value="Start" class="start">

    Hope this helps.