我一直在为此苦苦挣扎。我有一个推荐 slider 。没什么特别的,但我想向元素添加一个过渡类 2 秒,然后将其删除。
此外,我正在利用此类项目来鞭策自己更加努力。所以我尝试用 Promises 来做到这一点,并且推荐来自 Fetch 调用。
由于某种原因,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');
})
});
})
最佳答案
在您的代码中:
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)
})
您没有解决或拒绝 promise 。因此,promise 始终保持挂起状态,并且您的 then()
(或 catch()
如果发生错误)方法回调将永远不会被执行。
这是一个例子:
let prom = new Promise ((resolve,reject) => {
setTimeout(() => {
resolve('succes!')
}, 5000)
});
prom.then((res) => {console.log(res); });
关于javascript - Promise 和 setTimeout 不能一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53362913/