Javascript 是否在超时持续时间之前调用setTimeout()函数?

Javascript 是否在超时持续时间之前调用setTimeout()函数?,javascript,reactjs,timeout,Javascript,Reactjs,Timeout,我有一个React项目,我正在尝试建立一个旋转木马。我在旋转木马下有一个左右按钮和一些圆圈,可以分别选择幻灯片 要更改旋转木马中的幻灯片,我将使用间隔和超时的组合来播放幻灯片动画,并确保在用户未单击任何内容时循环运行: changeImageTimer(index = 0) { end = new Date().getMilliseconds(); console.info(end - start); setTimeout(()=> { this.a

我有一个React项目,我正在尝试建立一个旋转木马。我在旋转木马下有一个左右按钮和一些圆圈,可以分别选择幻灯片

要更改旋转木马中的幻灯片,我将使用间隔和超时的组合来播放幻灯片动画,并确保在用户未单击任何内容时循环运行:

changeImageTimer(index = 0) {
    end = new Date().getMilliseconds();
    console.info(end - start);
    setTimeout(()=> {
        this.addAnimation();
    }, this.props.timeToChangeImage - this.props.timeOfTransitionAnimation);
    animationTimeout = setTimeout(() => {
        if (this.state.index >= this.props.data.length - 1) {
            index = 0;
        } else {
            index = this.state.index + 1;
        }
        this.setState({index: index});
        this.removeAnimation();
    }, this.props.timeToChangeImage);
    animationInterval = setInterval(() => {
        setTimeout(()=> {
            this.addAnimation();
        }, this.props.timeToChangeImage - this.props.timeOfTransitionAnimation);
        animationTimeout = setTimeout(() => {
            if (this.state.index >= this.props.data.length - 1) {
                index = 0;
            } else {
                index = this.state.index + 1;
            }
            this.setState({index: index});
            this.removeAnimation();
        }, this.props.timeToChangeImage);
    }, this.props.timeToChangeImage);
}
选择单个幻灯片的按钮附带此功能:

clickSelector(index) {
    this.clearIntervalsAndTimers();
    this.setState({index: index});
    start = new Date().getMilliseconds();
    timeout = setTimeout(this.changeImageTimer(index), this.props.timeToHoldPictureAfterClick);
}
如您所见,我希望幻灯片保持不变,然后在一段时间后重新启动幻灯片的自动迭代

但是,“changeImageTimer”代码在“clickSelector”功能后立即运行,在设置的超时延迟后不会运行


为什么我会有这种行为?

这是因为参数。函数的第一个参数必须是参数引用。 希望这有帮助。

传递参数

 setTimeout(function() {
    this.changeImageTimer(index);
}, this.props.timeToHoldPictureAfterClick)
希望这有助于像这样修改:

    timeout = setTimeout(this.changeImageTimer.bind(this,index), this.props.timeToHoldPictureAfterClick);

超时调用一个函数,并传递它
changeImageTimer
返回的值。而是绑定函数,以便
setTimeout
获得一个预加载了参数的函数

    timeout = setTimeout(this.changeImageTimer.bind(this, index), this.props.timeToHoldPictureAfterClick);
另一方面,如果您将超时设置为类中的属性,那么在以后清除它们会更容易

this.timeout = setTimeout(this.changeImageTimer.bind(this, index), this.props.timeToHoldPictureAfterClick);
// ... later on in your code
clearTimeout(this.timeout)

如您所见
-您的代码很难理解。向我们展示
这个.props
对象。p、 s
设置超时
函数中可能会产生误导。感谢您提供有关使用属性的提示!