Arthurs Simans Arthurs Simans - 4 years ago 172
Javascript Question

How to make setInterval work?

So here is my code and I want to add 1 to total every second`

var doughnut = 0;
function myFunction(){

document.getElementById("total").innerHTML = " total: " + setInterval(doughnut +1, 1000) ;


}


Can you explain me how setInterval() works and where to put it?

Answer Source

setInterval accepts two arguments:

  1. The "What": The function to execute
  2. The "When": interval time in milliseconds to execute that function

Basically each second (1000 ms) the function increments the doughnut value and writes the updated value to the HTML element with id total.

Try this:

var doughnut = 0;

setInterval(function () {
    doughnut++;
    document.getElementById("total").innerHTML = " total: " + doughnut;
}, 1000);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download