h1元素文本不会使用javascript进行更改,而是在控制台中进行更改



我正在学习web开发,我正在尝试用javascript做最简单的事情来学习它的工作原理。我有这个问题,h1文本在页面上没有改变,但当我打开控制台时,它每次都会打印出改变后的值,下面是代码(提示,sleep((函数来自互联网,我对此一无所知,但它有效(:

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
<script>
let counter = 0;
function sleep(milliseconds) {
const date = Date.now();
let currentDate = null;
do {
currentDate = Date.now();
} while (currentDate - date < milliseconds);
}
function change(){
while(true)
{
document.querySelector("#show").innerText = counter;
counter++
console.log(document.querySelector("#show").innerText);
sleep(1000);
}
}  
</script>
</head>
<body>
<button onclick="change()" id="button" >COUNT</button>
<h1 id="show">0</h1>
</body>
</html>

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TEST</title>
<script>
function change() {
let counter = 0;
setInterval(() => {
document.querySelector("#show").innerText = counter;
counter++;
}, 1000);
}  
</script>
</head>
<body>
<button onclick="change()" id="button" >COUNT</button>
<h1 id="show">0</h1>
</body>
</html>

请尝试使用setInterval更改更改函数。您可以使用找到如何使用set intervalhttps://www.w3schools.com/jsref/met_win_setinterval.asp

最新更新