1

For some reason after I wrapped my js code in an immediately invoked function expression I'm getting progressBar not defined. Wondering why this is the case?

(function(){
    "use strict"

    var progressBar = function(){
        var bar = document.getElementById('pbar'),
        status = document.getElementById('status'),
        barValue = bar.value;

        status.innerHTML = barValue + "%";
        bar.value++;

        var increment = setTimeout("progressBar()", 50);
        if(bar.value == 100){
            status.innerHTML = '100% - Straight Besting';
            bar.value = '100';
            clearTimeout(increment);
        }
    }

    progressBar();

})()
0

1 Answer 1

6

When you pass a string to setTimeout, it is invoked in the context of the global window object.

Change the setTimeout line to:

var increment = setTimeout(progressBar, 50);

E.g.

(function() {
   let i = 0;
   let myfunction = function() {
      console.log(i++);
      if (i < 10) setTimeout(myfunction, 100);
   };

   myfunction();
})()

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

2 Comments

Thats interesting, why is that the case? Why when a function passed as a string into setTimout first arg, it is invoked in the context of the global not wihtin the scope?
It's because setTimeout is actually window.setTimeout. When you pass a string, you're actually passing in a string of "code" to execute, just like eval. The "code" does not contain any contextual information.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.