2013-06-25 33 views
1

出於某種原因,clearTimeout函數未在此腳本工作


腳本將

1)自動播放整個YouTube視頻,並使用突出在產品菜單中的積極一步setTimeout繼續下一步。這工作正常

2)當點擊菜單中的某個步驟時,應停止自動播放。
- 第1步:轉到YouTube視頻的第二個15 - 玩,直到第二個25
- 步驟2:轉到YouTube視頻的每秒25 - 玩到第二35
當你在一個菜單中點擊某些步驟setTimeout函數仍然運行,幾秒鐘後gotostep函數被調用,並且電影繼續錯誤的步驟。Cleartimeout JavaScript的工作不

請任何人都可以檢查嗎?

<script type="text/javascript"> 
    $(document).ready(function(){ 
    gotostep('C9x4vG_6Qcs','1','1');}); 

function gotostep(youtube,step,auto){ 
    var steparray=[15,25,35,48,58,65,79]; 
    var numbersteps=steparray.length-1; 
    var i=1; 
    var nextstep=parseInt(step)+1; 
    while(i<=numbersteps){ 
     if(step==i){ 
     document.getElementById('step'+i+'').style.background='url("bg-button-active.jpg")'; 
     var timeout=steparray[step]*1000-steparray[step-1]*1000+3000; 

     if(nextstep<=numbersteps && auto==1){ 
      var timer1=setTimeout('gotostep("'+youtube+'","'+nextstep+'","1")',timeout); 
     } 
     if(nextstep<=numbersteps && auto==0){ 
      clearTimeout(timer1); 

     } 

     }else{ 
     document.getElementById('step'+i+'').style.background='url("bg-button.jpg")'; 
     } 

     i++; 
    } 
    var thestart=parseInt(steparray[step-1]); 
    var theend=steparray[step]; 

    document.getElementById('productdemo-iframe').src="http://www.youtube.com/embed/"+youtube+"?autoplay=1&rel=0&start="+thestart+"&end="+theend+""; 


} 

HTML代碼

<div id="container"> 
<div id="left"> 
<iframe width="560" id="productdemo-iframe" height="315" src="http://www.youtube.com/embed/C9x4vG_6Qcs?rel=0&start=0" frameborder="0" allowfullscreen></iframe> 

</div> 
<div id="right"> 
<img src="logobw.jpg" alt="Logo" /> 
<ul id="productdemo"> 
<li><a id="step1" href="#" onclick="gotostep('C9x4vG_6Qcs','1','0');">1.&nbsp; Power button</a></li> 
<li><a id="step2" href="#" onclick="gotostep('C9x4vG_6Qcs','2','0');">2.&nbsp; Warming up</a></li> 
<li><a id="step3" href="#" onclick="gotostep('C9x4vG_6Qcs','3','0');">3.&nbsp; Insert cover</a></li> 
<li><a id="step4" href="#" onclick="gotostep('C9x4vG_6Qcs','4','0');">4.&nbsp; Cool down cover</a></li> 
<li><a id="step5" href="#" onclick="gotostep('C9x4vG_6Qcs','5','0');">5.&nbsp; Insert second cover</a></li> 
<li><a id="step6" href="#" onclick="gotostep('C9x4vG_6Qcs','6','0')">6.&nbsp; Turn off machine</a></li> 
</ul> 
</div> 
</div> 

回答

1

最簡單的解決將與window.timer1=更換var timer1=使TIMER1全球。當您取消超時時,timer1尚未設置,因爲它已超出範圍。在全局範圍內添加另一個變量只是爲了保存timer1值,但這是最快的修復方法。

一對夫婦的有關代碼的事情:

  1. 請不要在你的HTML使用onclick,你正在使用jQuery,所以你可以使用$(「slector」)上(「點擊」,..使用li的id來查看點擊的內容
  2. 將字符串傳遞給setTimeout是一個糟糕的主意,它會使用eval來弄清楚該怎麼做,看下面的代碼如何更好地做到這一點
  3. 您致電你的gotoStep變量step和auto作爲字符串,但稍後你將它們與數字進行比較。這是有效的,因爲你使用==而不是===。更好地傳遞numbe RS和比較排序,用===

數字要運行的setTimeout:

window.timer1=setTimeout(function(){ 
    gotostep(youtube,nextstep,1); 
},timeout); 
+0

由於它的工作! –

+0

@MichaelV另一件事;使用getDuration()來查看視頻播放的距離並使用它突出顯示菜單按鈕不是更好嗎?如果用戶暫停視頻,那麼您的代碼暫時失敗了嗎?以下是api文檔:https://developers.google.com/youtube/js_api_reference – HMR