-4

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?

Rene Pot
  • 24,681
  • 7
  • 68
  • 92
  • 6
    Why not google *"JavaScript setInterval"*? The first paramater for [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval) is a function to be called for each interval. – Spencer Wieczorek Feb 05 '17 at 19:23
  • @forrestmid That would do...nothing to update the `total` element. – T.J. Crowder Feb 05 '17 at 19:25
  • I googled it. And I did everythink like I understand it. And that isn't working – Jacob Fenrir Feb 05 '17 at 19:26
  • Then -- with respect -- you need to re-read those articles / tutorials. Much more carefully. Programming is an exercise in *details*. – T.J. Crowder Feb 05 '17 at 19:26
  • 2
    Possible duplicate of [How does setInterval and setTimeout work?](http://stackoverflow.com/questions/22051209/how-does-setinterval-and-settimeout-work) – m87 Feb 05 '17 at 19:38

1 Answers1

0

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);
Z-Bone
  • 1,534
  • 1
  • 10
  • 14