reactjs - 关于 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 函数。
解决方案
我认为这里实际发生的是 startClock 函数首先执行,但由于 setTimeout 中指定的时间是 1000 毫秒,所以睡眠函数在 GUI 更新之前启动,因此在睡眠完成之前不会更新 GUI。
推荐阅读
- angular - django 频道未初始化与 Angular 4 前端的连接
- elm - 发布 Elm19 包,第一个版本一次发布 18 个包 Elm19 已经发布
- getaddrinfo - getaddrinfo,分段错误
- java - 如何在 Chrome 和 Firefox 浏览器中通过 Selenium 切换帧?
- maven - Spring boot maven build 执行了我的数据库操作
- encryption - 使用一个人的名字来创建一个唯一的、不可逆的 ID
- perl - 后缀取消引用 say((\@a)->@*) v5.22
- java - Java android杀死服务
- reactjs - 如果 Redux Devtools 禁用,Immutable.Js 更新会出错
- delphi - 如何使用 TFileOpenDialog 回收内存?