setTimeout() 函数在超时持续时间之前调用
setTimeout() function called before duration of timeout?
我有一个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);
相关文章:
- 在jQuery中,短距离长持续时间的精细字体大小动画
- 创建一个倒计时计时器脚本,该脚本计算声音文件的持续时间,而不是特定的日期
- 输入视频文件时获取视频持续时间
- 无填充的滚动魔术持续时间
- 我需要在每5秒内调用一个函数,并重置持续时间
- jQuery动画的持续时间就像一个延迟
- 如何在特定时间重新加载page.php,例如:07:45.非持续时间,例如:每5秒
- 如何在dhtmlxgantt中显示灯箱中的开始日期、结束日期和持续时间
- Javascript - 具有音高和持续时间控制的文本到语音
- setTimeout() 函数在超时持续时间之前调用
- HTML 5 音频 :是否有在更改缓冲持续时间时触发的事件
- 如何获取所有旅行模式的距离和持续时间,例如驾驶,公交,骑自行车,在我的页面中步行以及将其存储在数据库中
- 当用户在文本框中输入日期时,如何计算一年的持续时间
- 如何使用 Javascript 将持续时间字符串解析为秒
- 速度.js动画两个属性时持续时间不同
- d3 动画中的持续时间
- Webkit-css随持续时间变化
- JS:设置src更改的动画持续时间
- 幻灯片放映中的第一张幻灯片超时(持续时间几乎是其他幻灯片的两倍)
- 使用.confrm()条件调用带有持续时间的jquery.fadeOutput()会打乱回调的时间