我想制作一个基数为16的javascript程序:
这段代码有效,但for循环太快,无法在HTML屏幕上呈现,即使是在非常快的计算机上,所以请告诉我一种减慢这些for循环的方法。
// Run this program at 60 fps
let frameRate = 1000 / 60;
// Have a boolean variable called isClicked that tracks if the user has clicked the button
let isClicked = false;
let integer = 0;
// Have the base 16 numbers be strings
let b16num1 = "";
let b16num2 = "";
// Have an array of all of the valid base16 numbers
let valid = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"];
const ClickButton = function() {
isClicked = true;
}
const runProgram = function() {
for (let i = 0; i < valid.length; i++) {
b16num1 = valid[i];
for (let j = 0; j < valid.length; j++) {
b16num2 = valid[j];
}
}
}
const updateHTML = function() {
let base16text = document.getElementById("base16text");
base16text.innerHTML = b16num1 + b16num2;
}
// Check if the user has clicked the button if they did then it runs the program
const checkIfClicked = function() {
// Run this if statement only once and check if its clicked
if (isClicked && integer < 1) {
// Run the program and update the HTML
setInterval(updateHTML, frameRate);
runProgram();
integer++;
// Stop repeating this function for a performance boost
clearInterval(repeat);
}
}
// Repeat the checkIfClicked function over and over again
let repeat = setInterval(checkIfClicked, frameRate);
&#13;
<button onclick="ClickButton()">Count in base 16!</button>
<br>
<h1 id="base16text"></h1>
&#13;
答案 0 :(得分:0)
问题在于,每当你的函数调用runProgram()
时,每秒发生16.6次,它就会一直有效!然后整个for循环运行,因此一直计入255.问题不在于帧速率,程序在你看到它之前就一直计算。
试试这个:
// Run this program at 60 fps
let frameRate = 1000 / 20;
var value = 0;
var repeat;
const startCounting = function()
{
repeat = setInterval(updateHtml, frameRate);
}
const updateHtml = function()
{
if (value < 255)
{
value++;
let base16text = document.getElementById("base16text");
base16text.innerHTML = value.toString(16).toUpperCase();
}
else
{
clearInterval(repeat);
}
}
每次调用函数时,这会为您的数字增加1!此外,toString会自动在您的基数之间进行转换。这非常方便。