How can I start stop async function on mouseenter and mouseleave event javascript?
I want function to be executed when mouse is not over swiperContainer and when it is on swiperContainer i want function to be stopped. I am not sure if its done corectly.
My async function and promise here:
const exit = function (){
return
}
const delay = async (ms = 1000) =>
new Promise(resolve => setTimeout(resolve, ms));
async function swiping() {
for(let i=0; i < img.length; i++){
img[i].classList.add('imghover');
button[i].classList.add('btnhover');
console.log(i);
await delay(3000);
img[i].classList.remove('imghover');
button[i].classList.remove('btnhover');
await delay(400);
if(i === 1 || i ===3 ){
swiper.slideNext();
await delay(300)
}
if(i === 3){
i = -1
}
}
}
// calling async function here
swiping();
}
const swiperConatiners = document.querySelectorAll('.swiper');
const auto = swiperConatiners.forEach(item =>{
item.addEventListener('mouseleave', event => {
swiping(exit)
})})
I already tried many things but still cant do it.
>Solution :
You can start and stop an async function in JavaScript using a combination of the mouseenter and mouseleave events and the clearTimeout function.
Here’s an example implementation:
javascript
// Define a variable to hold the timeout ID
let timeoutId;
// Define the async function
async function swiping() {
while (true) {
// Do something
await delay(1000);
}
}
// Start the async function
swiping();
// Listen for the mouseenter event on the swiper container
swiperContainer.addEventListener("mouseenter", () => {
// Clear the timeout to stop the function
clearTimeout(timeoutId);
});
// Listen for the mouseleave event on the swiper container
swiperContainer.addEventListener("mouseleave", () => {
// Set a timeout to start the function again after 1 second
timeoutId = setTimeout(swiping, 1000);
});
In this implementation, the timeoutId variable holds the ID of the timeout that will be set to start the function after a delay. When the mouse enters the swiper container, the clearTimeout function is called to stop the function from running. When the mouse leaves the container, the setTimeout function is called to start the function again after a delay.