I have an image carousel that by default rotates to the right. using setInterval() and changing the image every few seconds. I created two setInterval functions, one to rotate to the right and one to rotate to the left.
I then created an html arrow and added an onclick call to it to call the specific setInterval I wanted. The problem is the previous setIntervals dont turn off when new ones are called. I tried to use clearInterval but it wasnt working.
My code looks like:
const left_arrow = document.querySelector("#arrow");
var rotateRight = setInterval(()=>{
// do stuff
}, 3000)
var rotateLeft = setInterval(()=>{
// do stuff
}, 3000)
left_arrow.onclick = rotateLeft();
right_arrow.onclick = rotateRight();
I basically want to have the ability to click an arrow and have it rotate the flow of my images by calling different setInterval functions. I cant use any frameworks. Thank you.
SetInterval only executes an action every x milliseconds , so with your code you are going left and then right every three seconds. Here is my code that I think would work
direction = "right"
setInterval(()=>{
if(direction === "right") {
//do stuff to rotate right
} else {
//do stuff to rotate left
}
}, 3000)
left_arrow.onclick = () => {
direction = "left";
};
right_arrow.onclick = () => {
direction = "right";
};
So explaining what the code is doing the variable direction stores which direction the carousel should move, the code inside setInterval runs every 3 seconds, if the direction is right you run some code, otherwise you run other code. When you click the buttons it just sets the directions.
I think clearInterval will work on your scenary, may be you clearInterval on wrong time. if you're not sure,please paste more code.
secondly, const left_arrow = document.querySelector("#arrow");
#arrow element are named left_arrow, i don't know what is your element id for right_arrow, may be that's also a problem.
As @Dominik comments, the solution to stop the original interval is to use clearInterval
when you call setInterval
it
const left_arrow = document.querySelector("#arrow");
let currentInterval = null;
function rotateRight(){
return setInterval(()=>{
clearInterval(currentInterval)
// do stuff
}, 3000)
}
function rotateLeft(){
return setInterval(()=>{
clearInterval(currentInterval)
// do stuff
}, 3000)
}
left_arrow.onclick = ()=> {currentInterval = rotateLeft();}
right_arrow.onclick = ()=> {currentInterval = rotateRight();}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.