开发者

javascript setTimeout function out of scope

I am trying to call showUpload(); from within two setTimeouts. Neither works. It seems to be out of scope and I'm not sure why. I tried this.showUpload() which didn't work either.

 $(document).ready(function(){
            var progress_key = $('#progress_key').val();

            // this sets up the progress bar
            $('#uploadform').submit(function() {
               setTimeout("showUpload()",1500);
               $("#progressbar").progressbar({ value:0}).fadeIn();
            });


            // uses ajax to poll the uploadprogress.php page with the id
            // deserializes the json string, and computes the percentage (integer)
            // update the jQuery progress bar
            // sets a timer for the next poll in 750ms
            function showUpload() {
                $.get("/myid/videos/uploadprogress/" + progress_key, function(data) {
           开发者_开发知识库         if (!data)
                        return;

                    var response;
                    eval ("response = " + data);

                    if (!response)
                        return;

                    var percentage = Math.floor(100 * parseInt(response['bytes_uploaded']) / parseInt(response['bytes_total']));
                    $("#progressbar").progressbar({ value:percentage})

                });
                setTimeout("showUpload()", 750);
            }
        });

Thank you for your time.


As @Daniel said, this should work:

setTimeout(showUpload, 750);

Please note that the quotes should be removed (this is why it isn't being executed until the timeout runs out). Right now, you are passing a string, which is evaled when the timeout runs out. This eval will happen in a different scope, which is why you are seeing the problem you are seeing.

Instead, passing a reference to the showUpload function to setTimeout will allow your function to be executed later. Keep in mind that when it runs, it will be in a different scope, so you may have other scope issues, like with progress_key. You will need to create a closure around showUpload to capture that parameter.


It looks like you need to remove the parenthesis from showUpload in both your setTimeout calls. Otherwise you will be invoking the showUpload method instead of passing it as a parameter:

setTimeout(showUpload, 750);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜