0

我有一个 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);
        }


}
4

1 回答 1

3

这是 JS 初学者的常见错误。setTimeout承认两种第一个参数之一:a)文本,您可以在其中将要评估的 JS 代码置于范围之外(因此引用的变量可能未定义),不太有用。b)功能,例如我为此提出的修复,是替换行:

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

和:

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

如您所见,我将函数调用包装在另一个匿名函数中。为什么?仅仅是因为我需要传递参数,否则我只是调用它,而不是作为参数传递。

于 2012-05-02T03:09:05.090 回答