Reputation: 83
i have slideshow which i want to start with start() and stop with stop(). but it doesn't work. I have defined everything, included stop and start functions. Below i typed my html and javascript codes. When i click on Start button, it doesn't go automatically, i must click each time to get it in process
<DOCTPYPE! >
<html>
<head>
<style>
#imgs img {
float: center;
box-shadow: 5px;
}
input {
float: left;
margin-left: 20px;
}
input:last-child {
margin-left:5px;
}
</style>
<script src="ghgh.js"></script>
</head>
<body>
<div >
<img src="1.jpg" id="myPhoto" style="width: 600px; height: 400px;" />
</div>
<input type="button" value="start" onClick="start();" />
<input type="button" value="stop" onClick="stop();" />
<body>
</html>
javascript:
var myImage = document.getElementById("myPhoto");
var imageArray = ["1.jpg", "2.jpg", "3.jpg", "4.jpg"];
var imageIndex = 0;
function start () {
myPhoto.setAttribute("src", imageArray [imageIndex]);
imageIndex++;
if(imageIndex >= imageArray.length) {
imageIndex = 0;
}
}
var intervalHandle = setInterval (start (), 2000);
function stop() {
clearInterval(intervalHandle);
}
Upvotes: 0
Views: 43
Reputation: 971
Try this :
var myImage = document.getElementById("myPhoto");
var imageArray = ["1.jpg", "2.jpg", "3.jpg", "4.jpg"];
var imageIndex = 0;
var is_stop = 0;
var time = 0;
function start () {
is_stop =0;
myPhoto.setAttribute("src", imageArray [imageIndex]);
imageIndex++;
if(imageIndex >= imageArray.length) {
imageIndex = 0;
}
if(!is_stop){
time = setTimeout(start, 2000);
}
}
function stop() {
is_stop = 1;
if(time){
clearTimeout(time);
}
}
Upvotes: 2