gpt4 book ai didi

javascript - 在 setTimeout 中设置为 true 的变量总是 false?

转载 作者:行者123 更新时间:2023-11-30 19:04:03 24 4
gpt4 key购买 nike

好的,我想我有一个 this 上下文问题。我正在尝试仅在 mousedown 上设置计时器并在 mouseup 上重置计时器,使计时器设置为运动,以便 bool 标志在 5 秒后变为真。如果在重置计时器时(在鼠标弹起时)为真,则会触发函数 this.triggerRoomChange()

这是我所拥有的(它的节点):

   clearRoomChange(){

this.readyToChangeRooms = true;
console.log('READY');
};

onMouseDown()
{

this.mousedownTimeout = setTimeout(this.clearRoomChange, 5000);
this.mouseDown++;
}
onMouseUp()
{
clearTimeout(this.mousedownTimeout);

console.log(this.readyToChangeRooms);
if(this.readyToChangeRooms)
{
this.triggerRoomChange();
this.readyToChangeRooms = false;
}
this.mouseDown--;
}

打印 READY 在 5 秒后触发并且 setTimeout 似乎被清除,但是变量(在 MouseUp 上打印时)始终为 false。我在 this.clearRoomChange

中明确将其设置为 true

这是怎么回事?

最佳答案

超时改变范围。所以需要使用bind来维护作用域

this.mousedownTimeout = setTimeout(this.clearRoomChange.bind(this), 5000);

关于javascript - 在 setTimeout 中设置为 true 的变量总是 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59184053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com