Search code examples
javascripthtmltimersetintervalparseint

javascript timer to change content of a text


In html I have mentioned a class with id="txt"

<p id="txt">1</p>

I need to add 1 per every 500miliseconds interval. I used the following code but it didnot work.

function timedText() {
    var x = document.getElementById('txt');

    setInterval(function () {x= "(parseInt(x, 10)+ 1).toString(10)";},500);


}

The above function is called when a button is clicked.


Solution

  • JavaScript does not support string interpolation. I don't think you intended to use it, but anything within single quotes (') or double quotes (") will not be evaluated by JavaScript.

    To properly increment the value in your P tag, you will need this

    // valid
    x.innerHTML = (parseInt(x.innerHTML, 10)+ 1).toString(10);
    

    Not this

    // invalid
    x = "(parseInt(x, 10)+ 1).toString(10)";
    

    The above solution is pretty short-sighted, though. It couples your element, the counter increment, and the counter's delay all within a single function call. Not to mention, we're re-parsing the string to get the integer each time we increment.

    What if we wrap a little object around this that keeps the counter value in a variable? The object could also contain its own interval function and corresponding interval timer.

    Let's see what that might look like

    function Counter(elem, delay) {
      var value = parseInt(elem.innerHTML, 10);
      var interval;
    
      function increment() {
        return value += 1; // This 1 could be turned into a variable that allows
                           // us to count by any value we want. I'll leave that
                           // as a lesson for you !
      }
    
      function updateDisplay(value) {
        elem.innerHTML = value;
      }
    
      function run() {
        updateDisplay(increment());
      }
    
      function start() {
        interval = window.setInterval(run, delay);
      }
    
      // exports
      // This actually creates a function that our counter can call
      // you'll see it used below.
      //
      // The other functions above cannot be accessed from outside
      // this function.
      this.start = start;
    }
    

    Of course this Counter could be vastly simplified, but this demonstrates good separation of concerns. The Counter is initializes with the elements starting innerHTML and all operations of the counter are nicely divided into single-purpose functions. You can use this same approach for building much more complex objects, but still keep the code very sane and reusable.


    Now you can use your counter on any element

    // get element
    var elem = document.getElementById("txt");
    
    // create counter with element and delay of 500ms
    var counter = new Counter(elem, 500);
    
    // start the counter
    counter.start();
    

    jsfiddle demo