SetTimeout without polluting the global namespace?

Consider the following javascript:

$(function(){
  var private_function = function(){
    alert("private_function!");
  }

  setTimeout("private_function();", 1000);  

});

This gives the error "private_function not defined".

Is there a way to delay the execution of a private / anonymous function in javascript without polluting the global namespace and not opening it through the global module?

Thanks for any suggestions.

+3
source share
2 answers
$(function(){
  var private_function = function(){
    alert("private_function!");
  }

  setTimeout(private_function, 1000);  

});

OR

$(function(){
  var private_function = function(){
    alert("private_function!");
  }

  setTimeout(function(){
    private_function(); // with this method you can also pass some arguments
  }, 1000);  

});
+7
source

use setTimeout(private_function, 1000);to set Timeouthandler to function.

+1
source

All Articles