setTimeout() 函数在超时持续时间之前调用

setTimeout() function called before duration of timeout?

本文关键字:持续时间 调用 超时 函数 setTimeout      更新时间:2023-09-26

我有一个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 时会立即执行该方法?

传递参数

 setTimeout(function() {
    this.changeImageTimer(index);
}, this.props.timeToHoldPictureAfterClick)

希望这有帮助

你的超时调用一个函数,你传递它,无论changeImageTimer返回什么。而是绑定函数,以便setTimeout获取预加载了 args 的函数。

    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)

修改如下:

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