javascript:图像更改一定时间

时间:2017-05-28 18:27:49

标签: javascript image

我找到了这个脚本:

<html>
 <head>
<script type="text/javascript">
    var paths = ['assets/img/head.png','assets/img/tail.png'];
    var curPic = 1;
    var imgO = new Array();
    for(i=0; i < paths.length; i++) {
        imgO[i] = new Image();
        imgO[i].src = paths[i];
    }

    function swapImage() {
        curPic = (++curPic > paths.length-1)? 0 : curPic;
        imgCont.src = imgO[curPic].src;
        setTimeout(swapImage,200);
    }

    window.onload=function() {
        imgCont = document.getElementById('img');
        swapImage();
    }
</script>

</head>
<body>
<div>
    <img id="img"/>
</div>
</body>
</html>

这会重复更改图片的时间无限制,但我如何更改它会重复,例如只有5次?

1 个答案:

答案 0 :(得分:1)

只需使用跟踪器变量。

var to, times = 0; //<-- init the tracker, and a var for the timeout
function swapImage() {
    if (times == 5) {
        clearTimeout(to); //<-- if already 5 times, cancel timeout and...
        return;           //<-- ...quit
    }
    curPic = (++curPic > paths.length-1)? 0 : curPic;
    imgCont.src = imgO[curPic].src;
    to = setTimeout(swapImage,200); //<-- make the TO accessible via our var
    times++;
}