Reputation: 329
I have been struggling with this. I have a testimonial slider. nothing fancy but I want to add a transitioning class to the element for 2 seconds then remove it.
Also, I'm using this kind of projects to push myself harder. So I'm trying to do it with Promises, and testimonials are coming from Fetch call.
For some reason, setTimeout
is not working at all. Debugger says it is resolved without going inside of the timer.
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');
})
});
})
Upvotes: 2
Views: 938
Reputation: 36580
In your code:
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)
})
You are not resolving or rejecting the promise. Therefore the promise always remains in a pending state and your then()
(or catch()
in case of an error) method callback will never be executed.
Here is an example:
let prom = new Promise ((resolve,reject) => {
setTimeout(() => {
resolve('succes!')
}, 5000)
});
prom.then((res) => {console.log(res); });
Upvotes: 2
Reputation: 171679
You need to call resolve()
in the setTimeout()
.
arrows.forEach((item) => {
item.addEventListener('click',() => {
// no point in returning to an event listener
new Promise ((resolve,reject) => {
container.classList.add('transition');
setTimeout(() => {
/// do synchronous stuff
// then reolve promise
resolve()// include any value you want passed to next `then()`
}, 5000)
}).then(resolve =>{
testi(array,counter);
container.classList.remove('transition');
})
});
})
Upvotes: 2