Javascript Promises和setTimeout不在一起工作
我一直在努力解决这个问题。我有一个证明滑块。没什么特别的,但是我想在元素中添加一个转换类2秒钟,然后删除它 同时,我也在利用这种项目来让自己更加努力。所以我试着用承诺来做这件事,而且从回访电话中得到了证明 由于某种原因,Javascript Promises和setTimeout不在一起工作,javascript,settimeout,es6-promise,Javascript,Settimeout,Es6 Promise,我一直在努力解决这个问题。我有一个证明滑块。没什么特别的,但是我想在元素中添加一个转换类2秒钟,然后删除它 同时,我也在利用这种项目来让自己更加努力。所以我试着用承诺来做这件事,而且从回访电话中得到了证明 由于某种原因,setTimeout根本不起作用。调试器说它在不进入计时器的情况下被解析 arrows.forEach((item) => { item.addEventListener('click',() => { return
setTimeout
根本不起作用。调试器说它在不进入计时器的情况下被解析
arrows.forEach((item) => {
item.addEventListener('click',() => {
return new Promise ((resolve,reject) => {
container.classList.add('transition');
setTimeout(() => {
if (item.getAttribute('data-direction') == 'right'){
if(counter < array.length -1) {
counter ++;
} else {
counter = 0;
}
} else {
if(counter > 0) {
counter --;
} else {
counter = array.length -1;
}
}
}, 5000)
}).then(resolve =>{
testi(array,counter);
container.classList.remove('transition');
})
});
})
arrows.forEach((项目)=>{
item.addEventListener('单击',()=>{
返回新承诺((解决、拒绝)=>{
container.classList.add('transition');
setTimeout(()=>{
if(item.getAttribute('data-direction')=='right'){
if(计数器<数组长度-1){
计数器++;
}否则{
计数器=0;
}
}否则{
如果(计数器>0){
计数器--;
}否则{
计数器=数组长度-1;
}
}
}, 5000)
})。然后(解析=>{
testi(数组、计数器);
container.classList.remove('transition');
})
});
})
您需要在setTimeout()中调用resolve()
在代码中:
return new Promise ((resolve,reject) => {
container.classList.add('transition');
setTimeout(() => {
if (item.getAttribute('data-direction') == 'right'){
if(counter < array.length -1) {
counter ++;
} else {
counter = 0;
}
} else {
if(counter > 0) {
counter --;
} else {
counter = array.length -1;
}
}
}, 5000)
})
参数resolve
和reject
的存在是有原因的,您必须至少使用其中一个参数。为什么从click
处理程序函数返回一个承诺?它将忽略它。取而代之的是,确保在最后捕获(console.error)
errors。仅供参考,这里使用的setTimeout()
是次优的。如果您正在等待某个CSS转换完成,您应该只使用transitionend
事件,而不是计时器,直接监视转换的结束,而不是使用您自己的计时器。
return new Promise ((resolve,reject) => {
container.classList.add('transition');
setTimeout(() => {
if (item.getAttribute('data-direction') == 'right'){
if(counter < array.length -1) {
counter ++;
} else {
counter = 0;
}
} else {
if(counter > 0) {
counter --;
} else {
counter = array.length -1;
}
}
}, 5000)
})