randomnessthatsfunny
randomnessthatsfunny

Reputation: 123

How do you refresh inner HTML every second?

I have just started to learn how to code javascript from my college courses and I am having some trouble on this part that seems like it should work for me.

var cookieAmount = 0;
var cookiePerSecond = 0;
var cookiePerClick = 1;

function firstTimeLoad(){
   refreshClickStats();
}

function cookieClick(){
   cookieAmount += cookiePerClick;
   refreshClickStats();
}

function refreshClickStats(){
   var stats = "<p>You have " + cookieAmount + " cookies.<br>You have " + cookiePerSecond + " cookies per second.</p>";
   document.getElementById('cookieStats').innerHTML = stats;
}

function cookiePerSecondFunction(){
   cookieAmount =+ cookiePerSecond;
   refreshClickStats();
}

window.setInterval(cookiePerSecondFunction(), 1000);

The problem is that the setInterval always works once and then gives me a "cannot set property 'innerHTML' of null". But if I comment the refresh function from the cookiesPerSecondFunction it doesn't give me an error. So what am I doing wrong the the 1 second timer is only working once and giving me an error the rest of the time?

Thanks,

Mark Mueller

Upvotes: 1

Views: 1819

Answers (1)

Developer
Developer

Reputation: 6430

Is this what you are looking for?

var cookieAmount = 0;
var cookiePerSecond = 0;
var cookiePerClick = 1;

function firstTimeLoad() {
  refreshClickStats();
}

function cookieClick() {
  cookieAmount += cookiePerClick;
  refreshClickStats();
}

function refreshClickStats() {
  var stats = "<p>You have " + cookieAmount + " cookies.<br>You have " + cookiePerSecond + " cookies per second.</p>";
  document.getElementById('cookieStats').innerHTML = stats;
}

function cookiePerSecondFunction() {
  cookieAmount = ++cookiePerSecond;
  refreshClickStats();
}

window.setInterval(cookiePerSecondFunction, 1000);
<div id="cookieStats"></div>

Upvotes: 4

Related Questions