我试图在javascript中制作进度条,但是直到我 程序完成。程序仍在运行时如何更新?
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="main" onclick="my()">1</div>
<button onclick="myFunction()">start</button>
<script>
function myFunction() {
for(var i=0;i<1000000;i++){
document.getElementById("main").innerHTML=i;
}
}
</script>
</body>
</html>
答案 0 :(得分:2)
使用setInterval
方法,该方法在后台运行而不会阻塞。达到条件后,您可以使用clearInterval
方法清除间隔。
function myFunction() {
// get element reference and cache in a variable
let main = document.getElementById("main"),
// initialize i as 0
i = 0;
// keep interval reference for clearing once i reached 1000000
let intrvl = setInterval(() => {
// check value of i and increment, if reached 1000000 clear the interval
if (i++ === 1000000) clearInterval(intrvl);
// update the content of main element
main.innerHTML = i;
}, 1000); // set required delay in millisecond, any value lesser than 10 will be automatically converts to 10
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="main" onclick="my()">1</div>
<button onclick="myFunction()">start</button>
<script>
function myFunction() {
let main = document.getElementById("main"),
i = 0;
let intrvl = setInterval(() => {
if (i++ === 1000000) clearInterval(intrvl);
main.innerHTML = i;
},1000);
}
</script>
</body>
</html>
答案 1 :(得分:0)
我用setInterval
代替了cicle,我用parseInt()
来获取div innerHTML的整数值,然后将其递增
setInterval(myFunction, 1000)
每1000毫秒运行myFunction()
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="main" onclick="my()">1</div>
<button onclick="setInterval(myFunction, 1000)">start</button>
<script>
function myFunction(){
var value = parseInt(document.getElementById("main").innerHTML);
document.getElementById("main").innerHTML=value+1;
}
</script>
</body>
</html>