2012-05-02 61 views
0

我有一個JavaScript函數,通過選中的複選框列表並上傳每個複選框的視頻文件。我試圖確保在我開始上傳過程之前將視頻轉碼爲較小的格式。我用來跟蹤已完成轉碼過程的陣列視頻中的索引。在開始給定視頻的上傳過程之前,我檢查以確保計數器> = id。如果計數器太低(文件還沒有轉碼),我使用setTimout()再次調用uploadVideos函數。它永遠不會再次調用uploadVideos功能,因爲我再也看不到警報彈出窗口。JavaScript setTimeout()沒有實際執行它的功能?

我該如何得到這個工作?

function uploadVideos(id, videos, selected, boxes) { 

     var status = document.getElementById('currentUploadStatus'); 
     // need to deal with element an array 
     var fields = videos[id].split(":", 2); 
     var playlist = document.getElementById('playlist'); 
     var dataString = 'videoId='+ fields[0] + '&playlist=' + escape(playlist.value); 

// need to determine the maxTranscodedId 
     var counter = document.getElementById('counter'); 
     alert('counter: ' + counter.innerHTML + " id: " + id); 
     if (counter.innerHTML >= id) { 

      id++; 
      status.innerHTML = "<b class='status'>Uploading Bout #" + fields[1] + " (" + id + " of " + videos.length + ")</b>"; 

      $.ajax({ 
       type: "GET", 
       url: "floUpload.php", 
       data: dataString, 
       success: function(txt) { 
        if (txt != 'Success') { 
         alert(':' + txt + ':'); 
        } 

        if (id < videos.length) { 
         uploadVideos(id, videos, selected, boxes); 

        } else { 
         //re-enable the start button 
         var startButton = document.getElementById('start'); 
         startButton.disabled = false; 

         status.innerHTML = "<b class='status'>Upload Complete</b>"; 
         alert('Upload Completed'); 

        } 

        //deselect the checkbox 
        if (boxes == 1) { 
         document.videos.video.checked = false; 
         document.videos.video.style.display = 'none'; 
        } else { 
         document.videos.video[selected[id-1]].checked = false; 
         document.videos.video[selected[id-1]].style.display = 'none'; 
        } 
       }, 
       async: true 

      }); 



     } else { 
      // timer call myself the same way I was called 

      status.innerHTML = "<b class='status'>Upload waiting for trancode.</b>"; 
      var t=setTimeout("uploadVideos(id, videos, selected, boxes)",3000); 
      //var t=setTimeout("alert('waking')",3000); 
     } 


} 
+2

不要使用'setTimeout(fn,t)',其中'fn'是一個字符串,而不是使用'setTimeout(function(){'這裏字符串的內容'},t)'。 –

+1

請勿使用['escape'](https://developer.mozilla.org/en/DOM/window.escape),請使用['encodeURIComponent'](https://developer.mozilla.org/en/的JavaScript /參考/ Global_Objects/encodeURIComponent方法)。 –

回答

3

這是JS初學者常見的錯誤。 setTimeout承認兩種第一參數中的任意一種: a)文本中,您可以將JS代碼評估爲超出範圍(因此引用的變量可能未定義),但不是很有幫助。 b)功能,比如我提出這個修復,是替代線路:

setTimeout("uploadVideos(id, videos, selected, boxes)",3000); 

有:

setTimeout(function(){ 
    uploadVideos(id, videos, selected, boxes); 
},3000); 

正如你可以看到我在裏面包裹另一個匿名函數調用功能。爲什麼?只是因爲我需要傳遞參數,否則我只是調用它,而不是作爲參數傳遞。