gpt4 book ai didi

javascript - 一组间隔后生成数字

转载 作者:行者123 更新时间:2023-11-30 16:39:20 26 4
gpt4 key购买 nike

我正在尝试每隔 20 秒显示一次随机数。我下面的代码仅在浏览器刷新时显示。我想要发生的是在 1 - 100 的无限循环中不刷新浏览器的数字变化

function visitorounter(){
var randomnumber=Math.floor(Math.random()*100);
document.write("<strong>"+randomnumber+"</strong>");
}

visitorounter()

最佳答案

您自己的方法的问题很可能是在文档完成加载后使用 document.write;这会导致页面重新加载以显示或完全被提供的 HTML 字符串覆盖。

我建议采用以下方法(作为众多替代方法之一):

// using a named function to generate the random numbers:
function randomNumber () {
return Math.floor(Math.random() * 100);
}
function visitorounter() {

// retrieving the element in which the random number
// should be shown:
var elem = document.getElementById('randomNumber');

// updating that element's text-content to show the
// first random number immediately:
elem.textContent = randomNumber();

// setting the interval (20000ms) after which the
// the supplied anonymous function should be run:
window.setInterval(function () {

// updating the text of the element:
elem.textContent = randomNumber();
}, 20000);
}

visitorounter();

function randomNumber() {
return Math.floor(Math.random() * 100);
}

function visitorounter() {
var elem = document.getElementById('randomNumber');
elem.textContent = randomNumber();
window.setInterval(function() {
elem.textContent = randomNumber();
}, 20000);
}

visitorounter();
<p id="randomNumber"></p>

外部 JS Fiddle demo用于实验和开发。

引用资料:

关于javascript - 一组间隔后生成数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32243347/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com