【问题标题】:On window load run one function, after 10seconds run another (setTimeout)在窗口加载时运行一个函数,10 秒后运行另一个函数(setTimeout)
【发布时间】:2020-07-31 11:42:09
【问题描述】:

我正在尝试为两种颜色创建间隔或超时。在页面加载时,我希望我的第一个函数 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;
        }
    }

【问题讨论】:

  • 抱歉,您的代码没有任何意义,您没有更改任何颜色,而是看到 "{% static "main_platform/media/red_circle.png" %}",我假设它是红色圆圈图像的路径,因此与更改颜色无关,而是图像,您可以发布包含 HTML 代码的实时版本
  • 我知道这没有意义..我试图让它有意义,也许不要看代码,而是看我正在尝试做的事情的描述。我已经编辑了评论。 :)
  • 好的,但是你说我希望窗口加载时颜色是灰色的,那为什么要等半秒钟呢?而不是 onload 的事件监听器
  • 没有理由,主要是因为我不知道如何让它快速执行,我尝试了 0 但不确定是否会起作用。所以,你建议这一切都在一个 window.onload 函数中,默认为灰色,10s后变为红色?
  • 是的,更好的是你为什么不从一开始就将圆圈设为灰色,我的意思是在你的HTML代码中,有什么原因吗?然后你只需使用一个setTimeout来改变它10 秒,这让它变得简单易行

标签: javascript settimeout setinterval


【解决方案1】:

您可以在页面加载时使用它:

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();">

【讨论】:

  • 但 setTimeout 异步运行,因此 get_color(red) 不会等待,而是立即执行,这会使您的答案错误
猜你喜欢
  • 1970-01-01
  • 2018-05-10
  • 1970-01-01
  • 2021-08-07
  • 2020-06-11
  • 1970-01-01
  • 2014-09-28
  • 2012-06-04
  • 1970-01-01
相关资源
最近更新 更多