0

I have a function which showing progress of uploading files to the server:

function progress(event) { ... } ... for (var i = 0; i<files.length; i++) { xhr.upload.onprogress = progress; } 

progress function is in for loop, and executes once for every file. In progress function I want to write how many percent is uploaded, I can do it for one file, but if I uploading not one file, then I don't know how to make progress for every file. Can I add a parameter of loop to progress function?

1 Answer 1

1

You can use an anonymous function to give progress function additional parameter:

function progress(event, file) { ... } for (var i = 0; i<files.length; i++) { xhr.upload.onprogress = function(event) { progress(event, files[i]); } } 

But this code will not work because progress will take the last file item every time. To avoid it you must use a closure:

function progress(event, file) { ... } for (var i = 0; i<files.length; i++) { (function(xhr, file) { xhr.upload.onprogress = function(event) { progress(event, file); } })(xhr, files[i]); } 

P. S. Sorry, my first anwser was wrong, I've deleted it.

Sign up to request clarification or add additional context in comments.

2 Comments

спасибо) but can I do it without anonymous function?
What for? If you define progress function inside the closure, it will have access to parent context (xhr and file variables). But I don't think it's a good idea in the general case: the new function will be created in memory at each cycle iteration. Пожалуйста :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.