迴圈的問題

browser_loop_problem

<body>
    <script>
        function getPicPath(idx) {
            var s = (("0000") + idx.toString()).slice(-4);
            s = s + ".jpg";
            return (s);
        }
        for (i = 0; i < 100; i++) {
            console.log(getPicPath(i));
        }
    </script>
</body>

keyword: non-blocking language

timer 事件

setInterval()

setTimeout()

問題

onload 事件

window.onload

預設是當整個網頁都載入的時候( (images, css, scripts, etc.)才觸發事件,但是看瀏覽器而定。

document.onload

DOM 準備好時候才觸發,可能影像和其他外部資源還沒載入。

亂數播放

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>browse pic</title>
    <script src="browsepic1.js"></script>
    
</head>
<body>
    <img id="imgPlay" src="0000.jpg" width="50%" height="50%">
</body>
</html>
function getPicPath(idx)
{
 var s =(("0000")+idx.toString()).slice(-4);
 s=s+".jpg";
 return(s);
}
function rndIdx(maxIdx){
 return (Math.floor(Math.random()*maxIdx)+1);
}
function changePic(e)
{
    var aPath=getPicPath(rndIdx(10));
    imgPlay.src=aPath;
}
var mtask;

window.onload=function(e){
    mtask = setInterval(changePic,1000);
    
}


問題:

  1. 如何停止?
    hint: clearInterval(?handler) ,在這個範例中,handler 是誰?

練習:

讓他跑一段時間以後停止。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>browse pic</title>
    <script src="browsepic1.js"></script>
    <script src="browsepic2.js"></script>
    
</head>
<body>
    <img id="imgPlay" src="0000.jpg" width="50%" height="50%">
</body>
</html>
 

function stopPlay()
{
    clearInterval(mtask);
    alert("stop!");
}
var oldload=window.onload;
window.onload = function(e){
    oldload && oldload();  
    setTimeout(stopPlay,1000*10);
}

討論:

window.addEventListener("onload",function(e){...})

練習:

循序播放?

function getPath(idx)
{
    return (("00000"+String(idx)).slice(-4)+".jpg");
}
var idx=0;
function mPlay()
{
    imgPlay.src=getPath(idx);
    idx=(idx+1) % 20 ;

}
setInterval(mPlay,200);
<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>

</head>
<body>
   <img id='imgPlay'>
   <script src="play1.js"></script>    
</body>
</html>

note: 其中 #8,#9 不能對調,例如:

   <script src="play1.js"></script>  
   <img id='imgPlay'>

JS載入的時候,不知道甚麼是imgPlay

問題:

寫成如下的程式碼,會怎樣?

function getPath(idx)
{
    return (("00000"+String(idx)).slice(-4)+".jpg");
}
for (var i=0;i<20;i++)
{
    imgPlay.src=getPath(i);
}

為甚麼?