首页 > 解决方案 > 关于 React 函数执行顺序的问题

问题描述

在下面的代码中,为什么在 startClock 函数之前执行了 sleep 函数?

handleClick = () => {

        this.startClock();
        this.sleep(5000);
}

startClock = () => {
        var today = new Date();
        var h = today.getHours();
        var m = today.getMinutes();
        var s = today.getSeconds();
        // add a zero in front of numbers<10
        m = this.checkTime(m);
        s = this.checkTime(s);
        document.getElementById("txt").innerHTML = h + ":" + m + ":" + s;
        console.log(h + ":" + m + ":" + s);
        var t = setTimeout(function(){this.startClock()}.bind(this), 1000);
      };

checkTime = (i) => {
        if (i < 10) {
          i = "0" + i;
        }
           return i;
        };

sleep = (timeout) => {
        var begin = new Date();
        while (new Date() - begin < timeout) {
        }
      };

我希望 startClock 函数首先执行,但 sleep 函数首先执行,然后是 startClock 函数。

标签: reactjs

解决方案


我认为这里实际发生的是 startClock 函数首先执行,但由于 setTimeout 中指定的时间是 1000 毫秒,所以睡眠函数在 GUI 更新之前启动,因此在睡眠完成之前不会更新 GUI。


推荐阅读