Reputation: 121
I have a function that automatically loads when the pages opens. I want the function to stop running after "onclick". I want the slideshow to stop running automatically after clicking a button.
<html>
<head>
<script type="text/javascript">
function changeImage(x){
imageNumber += x;
if(imageNumber > imageLength){
imageNumber = 0;
}
if(imageNumber < 0){
imageNumber = imageLength;
}
document.getElementById("slideshow").src = images[imageNumber];
document.getElementById("caption").innerHTML = caption[imageNumber];
return false;
}
function autoRun(){
//This function simply makes the slideshow change slides every 5 seconds.
setInterval("changeImage(1)", 5000);
}
function clearFunction(){
//This function needs to stop the autoRun function.
//If the user wants to manual flip through the slides,
//I don't want the slides to continue changing automatically
}
</script>
</head>
<body onload="autoRun()">
<a href="#" onclick="changeImage(-1); clearFunction();">Previous Slide</a>
<a href="#" onclick="changeImage(1); clearFunction();">Next Slide</a>
</body>
</html>
Upvotes: 0
Views: 161
Reputation: 521
You need to use clearInterval
var interval = 1;
function autoRun(){
//This function simply makes the slideshow change slides every 5 seconds.
interval = setInterval(changeImage, 5000, 1);
}
function clearFunction(){
clearInterval(interval);
}
Upvotes: 0
Reputation: 1782
You can make a window interval that calls autoRun
every 5000 milliseconds.
// anywhere in your script, outside of any function
let timer = window.setInterval(changeImage, 5000);
In the clearFunction
function, just do
window.clearInterval(timer);
See window.setInterval.
Upvotes: 0
Reputation: 138237
Intervals can be cleared:
var interval;
function autoRun(){
//This function simply makes the slideshow change slides every 5 seconds.
interval=setInterval(changeImage, 5000,1);
}
function clearFunction(){
if(interval) clearInterval(interval);
}
Upvotes: 1
Reputation: 1209
You can put all the code in autoRun()
inside an if(flag)
with flag
being a boolean that is initially set to true
and then you can set flag=false
inside clearFunction()
, so whenever clearFunction()
is called, flag
is set to false
and the code inside autorun()
won't execute because it won't pass the if(flag)
check.
Note that flag
needs to be a global variable.
Upvotes: 0