在窗口加载时运行一个函数,10秒后运行另一个函数(setTimeout)



我正在尝试为两种颜色创建一个间隔或超时。在页面加载时,我希望我的第一个函数grayColor运行,直到10秒后,我希望运行我的redColor,替换那个颜色。

我可以在下面展示我所尝试的,但我认为这是非常错误的。我相信一旦红色超时需要运行,我需要某种类型的清除灰色超时?欢迎提出任何建议!谢谢

编辑:下面的例子不是实际的项目,它的代码相当复杂。我们试图做的是当浏览器加载时,圆圈应该是灰色的,10秒后变成红色。

当前想法

let red = "{% static "main_platform/media/red_circle.png" %}";
let grey = "{% static "main_platform/media/grey_circle.png" %}";    
let timeout;
function greyColor() {
timeout = setTimeout(get_color, 500);
return timeout;
}
function redColor() {
timeout = setTimeout(get_color: 10000);
return timeout;
}
function get_color(choice) {
if (greyColor()) {
return grey;
} else if(redColor) {
return red;
}
}

页面加载时可以使用此选项:

async function set_colors(){
get_color(grey); //Get the color and do what you need to do;
await sleep(10000);  //Call function "Sleep" and wait 10000ms(10s)
get_color(red);//Get the color and do what you need to do;

}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

HTML:

<body onload="set_colors();">

最新更新