1

1.- Why is it necessary to return a function from updateFn? If I run this code commenting the return function the progress bar would go directly to 100 %.

2.- What are the differences when returning a function compared to just having the logic inside updateFn that makes returning a function necessary?

 Ext.onReady(function(){
    Ext.MessageBox.show({   
        title       : 'Wait',
    msg         : 'Hold',
    progressText: "on going ...",
    width       : 300,
    progress    : true,
    closable    : false   
});

var updateFn = function(num){
    console.log('inside updateFn');
    return function(){ //if I comment this line the function gets immediately called (when executed from the for loop)
        console.log(num);
        if(num == 6){
            Ext.MessageBox.updateProgress(100, 'All items saved puto');
            Ext.Function.defer(Ext.MessageBox.hide, 1500, Ext.MessageBox);
        }
        else{
            var i = num / 6;
            var pct = Math.round(100 * i);
            Ext.MessageBox.updateProgress(i, pct + '% completed');
        }


    }
};

for(var i = 1; i < 7; i++){
    console.log('inside for');
    setTimeout(updateFn(i),i * 2000); 
}




});
code4jhon
  • 5,725
  • 9
  • 40
  • 60

1 Answers1

2
  1. : setTimout expects a valid reference to a function as first parameter. If you wouldn't return a function from updateFn then you wouldn't pass a parameter to setTimout.

  2. : you can create a closure by returning a function (from a function). To understand closures and what they are good for I recommend you to read this: How do JavaScript closures work?

Why you need to return a closure here: you pass a number (variable i) to the updateFn-function. Then you use this number in the returned function. If you wouldn't do so then you could't use that variable.

You're probably asking yourself now why not doing it like this:

for(var i = 1; i < 7; i++){
    setTimeout(function() {
        updateFn(i); // i is always the same variable (reference)
    }, i * 2000); 
}

However this does not work because the variable i isn't 'preserved'. You then would have to do it like this:

for(var i = 1; i < 7; i++){
    setTimeout((function(i) { // f.e. make use of a self-execution function
        return function() {
            updateFn(i); // i is now the variable of the inner scope and thus preserved
        };
    })(i), i * 2000); 
}

and this is exactly what you are already doing.

Community
  • 1
  • 1
sjkm
  • 3,887
  • 2
  • 25
  • 43