我想创建一个程序来递归地更改文本的颜色。
我已经创建了一个带有随机颜色代码的for(){}
循环,以便尝试对其进行递归。
for(var x = 0; x > -1; x++){
document.getElementById("k").style.color = '#'+(0x1000000+
(Math.random())*0xffffff).toString(16).substr(1,6)}
<p id="k">Yeet</p>
实际结果是颜色保持默认值,即黑色。我希望它每次运行(无限期)都会改变颜色。
答案 0 :(得分:6)
您必须使用setInterval()
方法来异步运行,而不会阻止主执行。
setInterval(() => document.getElementById("k").style.color = '#' + (0x1000000 +(Math.random()) * 0xffffff).toString(16).substr(1, 6),500)
<p id="k">Yeet</p>
如果您想停下来,请使用clearInterval()
方法清除间隔。
let i = 0;
const inter = setInterval(() => {
document.getElementById("k").style.color = '#' + (0x1000000 + (Math.random()) * 0xffffff).toString(16).substr(1, 6);
// to clear after 10 colors
if (i++ === 10) clearInterval(inter);
}, 500)
<p id="k">Yeet</p>
答案 1 :(得分:0)
/** Bad recursive pattern.
*
* All recursive methods should have a base case,
* I assume you want the change to stop at some point,
* if not you have an infinite loop running.
*
* This function can still time out if it takes too long to hit "theLastColor"
*/
function recursiveColorChange(id, currentColor) {
const theLastColor = '#some-value';
if (currentColor === theLastColor) {
return;
}
const randomColor = '#' + (0x1000000 + (Math.random()) * 0xffffff).toString(16).substr(1, 6);
document.getElementById(id).style.color = randomColor;
return recursiveRandomColor(id, randomColor);
}
但是,使用纯递归代码可防止控制颜色更改Z_BEST_SPEED。 如@ pranav-c-balan所述,我认为最好使用setTimeout。 您仍然可以使用clearTimeout();
/** Better setTimeOut pattern.
*
* You can pass a lastColor value if you want it to stop if it reaches a color.
* Or you can just pass it an id and a speed (in milliseconds) and it will run forever without breaking your code.
*/
function repeatColorChange(id, speed, lastColor) {
const myTimeOut = setTimeout(() => {
const randomColor = '#' + (0x1000000 + (Math.random()) * 0xffffff).toString(16).substr(1, 6);
document.getElementById(id).style.color = randomColor;
if (randomColor === lastColor) {
clearTimeout(myTimeOut);
}
}, speed);
}