[英]How to count all the numbers that is generated?
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.您只调用
add()
一次。 You probably want to call it from inside the generate()
function.您可能想从
generate()
函数内部调用它。 Additionally var count = 0
should be outside of the add()
function so that its value gets persisted across calls.此外,
var count = 0
应该在add()
函数之外,以便它的值在调用之间保持不变。
Sidenotes:旁注:
You increase count
two times per add()
call.每次
add()
调用add()
count
增加两次。
The outer setTimeout
inside generate()
is useless. generate()
的外部setTimeout
没有用。
number
is a leaking global, you should declare it with var
number
是一个泄漏的全局变量,你应该用var
声明它
I recommend you to use setInterval
for repeated calls, and the data
attribute to store the current count.我建议您使用
setInterval
进行重复调用,并使用data
属性来存储当前计数。
Extract the calls of document.getElementById
to avoid look-for elements per setInterval
cycle.提取
document.getElementById
的调用以避免在每个setInterval
循环中查找元素。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.