我有一个JavaScript函数,它通过一个选中的复选框列表,并为每个复选框上传一个视频文件。我正在尝试确保在开始上传过程之前将视频转码为较小的格式。我用来跟踪已完成转码过程的阵列视频中的索引。在开始给定视频的上传过程之前,我检查确定计数器是> = id。如果计数器太低(文件尚未转码),我使用setTimout()再次调用uploadVideos函数。似乎再也没有调用uploadVideos功能,因为我再也没有看到过警告弹出窗口。
我怎样才能让它发挥作用?
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);
}
}
答案 0 :(得分:3)
这是JS初学者的一个常见错误。 setTimeout
允许以下两种第一参数之一:
a)文本,您可以在其中将JS代码放在范围之外(因此引用的变量可能未定义),不太有帮助。
b)功能,例如我为此提出的修正,是替换线:
setTimeout("uploadVideos(id, videos, selected, boxes)",3000);
使用:
setTimeout(function(){
uploadVideos(id, videos, selected, boxes);
},3000);
正如您所看到的,我将函数调用包装在另一个匿名函数中。为什么?只是因为我需要传递参数,否则我只是调用它,而不是作为参数传递。