在JS图像sideshow中重置间隔

时间:2013-01-09 11:13:21

标签: javascript

如何在JavaScript中重置间隔onclick。我有以下教程,一切正常,我可以通过点击继续重新开始。

var myImage = document.getElementById("mainImage");

var imageArray = ["_images/overlook.jpg","_images/winery_sign.jpg","_images/lunch.jpg",
             _images/bigSur.jpg","_images/flag_photo.jpg","_images/mission_look.jpg"];
                 var imageIndex = 0;


function changeImage (){
    myImage.setAttribute("src",imageArray [imageIndex]);
    imageIndex++;

if (imageIndex >= imageArray.length){
    imageIndex = 0;
}
 }

 var intervalHandler = setInterval(changeImage, 5000);
myImage.onclick = function (){
    clearInterval(intervalHandler);
}

**// The code below doesn’t work**

 var intervalReset = clearInterval;
myImage.onclick = function (){
    setInterval(intervalReset);
};

2 个答案:

答案 0 :(得分:0)

您正在设置onclick两次,替换处理程序,因此只有后面的定义才会计算。请改用addEventListener

myImage.addEventListener("click", function() {
    //first set of stuff
});

myImage.addEventListener("click", function() {
    //more stuff
});

只有你的第一个功能才有意义。您可能还想将imageIndex重置为0.

总而言之,您的代码应该类似于:

var intervalHandler = setInterval(changeImage, 5000);
myImage.addEventListener("click", function() {
    clearInterval(intervalHandler);
    imageIndex = 0;
    intervalHandler = setInterval(changeImage, 5000); //restart again
});

答案 1 :(得分:0)

setInterval返回一个间隔ID,用于清除间隔:

var intervalDuration = 5000;
myImage.onclick = function (){
    clearInterval(intervalHandler);
    // Assumes intervalDuration is defined
    intervalHandler = setInterval(changeImage, intervalDuration);
};