Write a setInterval() function that increases the count by 1 and displays the new count in counterElement every 300 milliseconds. Call clearInterval() to cancel the interval when the count displays 5.



var count = 0;


var counterElement = document.getElementById("counter");


counterElement.innerHTML = count;



/* Your solution goes here*/

Respuesta :

Answer:

  1. var count = 0;
  2. var counterElement = document.getElementById("counter");
  3. counterElement.innerHTML = count;
  4. var a = setInterval(
  5.    function(){  
  6.        count++;
  7.        counterElement.innerHTML = count;
  8.        if(count == 5){
  9.            clearInterval(a);
  10.        }
  11.    }
  12.        , 300);

Explanation:

The solution code is given from Line 6 - 15.  

setInterval function is a function that will repeatedly call its inner function for an interval of time. This function will take two input, an inner function and the interval time in milliseconds.  

In this case, we define an inner function that will increment count by one (Line 8) and then display it to html page (Line 9). This inner function will repeatedly be called for 300 milliseconds. When the count reaches 5, use clearInterval to stop the innerFunction from running (Line 11 - 13).