What i'm trying to do:
Actual Results
Expected Results
function generator() { number = Math.floor(Math.random() * 11); setTimeout(function() { setTimeout(function() { document.getElementById("demo").innerHTML = number; generator(); }, 5000); }) } function add() { var count = 0 var element = document.getElementById("demo").innerHTML; if (element.innerHTML) { count++ document.getElementById("demo1").textContent = count++; } } generator(); add();
<p id="demo"></p> How many numbers was generated? <p id="demo1"></p>
You call add()
only once. You probably want to call it from inside the generate()
function. Additionally var count = 0
should be outside of the add()
function so that its value gets persisted across calls.
Sidenotes:
You increase count
two times per add()
call.
The outer setTimeout
inside generate()
is useless.
number
is a leaking global, you should declare it with var
I recommend you to use setInterval
for repeated calls, and the data
attribute to store the current count.
Extract the calls of document.getElementById
to avoid look-for elements per setInterval
cycle.
var demoElem = document.getElementById("demo"); var countElem = document.getElementById("demo1"); function generator() { var interId = setInterval(function() { var number = Math.floor(Math.random() * 11); demoElem.textContent = number; add(); }, 2000); } function add() { countElem.dataset.count = Number(countElem.dataset.count) + 1; countElem.textContent = countElem.dataset.count; } generator();
<p id="demo"></p> How many numbers was generated? <p id="demo1" data-count='0'></p>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.