简体   繁体   English

如何计算所有生成的数字?

[英]How to count all the numbers that is generated?

What i'm trying to do:我正在尝试做的事情:

  • Count all the numbers that is generated every 5 seconds.计算每 5 秒生成的所有数字。

Actual Results实际结果

  • Generates only numbers but, doesn't count them.只生成数字,但不计算它们。

Expected Results预期成绩

  • Counts all the numbers that is generated and shown next to the question.计算生成并显示在问题旁边的所有数字。

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM