Cannot access element from named javascript function

I have a javascript function that works fine if it is anonymous, but stops working when I change it to a name .. Why?

here is the code that works:

setInterval( function(){
<% @root.children.all(:order  => "idx DESC").each do |child| %>
        var text2 =    "<%= child.content %>";
      var pjs = Processing.getInstanceById("mysketch2");
    pjs.update(text2);
    <% end %>

}, 3000)

      

Here is the code that doesn't work.

<script>
  var interval = setInterval(drawGraph(),1000);
    function drawGraph(){
  <% @root.children.all(:order  => "idx DESC").each do |child| %>
        var text2 =    "<%= child.content %>";
        var pjs = Processing.getInstanceById("mysketch2");
        pjs.update(text2);
      <% end %>

     }

</script>

      

I am getting "Uncaught TypeError: Can't call the" update "method is undefined. The weirdest part is I can see the Processing.js window getting drawn on the screen, but it's .. With the working version (the first in this post) everything fine and the contents of the window are drawn as well ..

I tried to put pjs in a global variable outside of the drawGraph () function, but no luck ... What am I missing? Thank!

+3


source to share


2 answers


It should be

setInterval(drawGraph,1000);

      

not



setInterval(drawGraph(),1000);

      

Also, the function must be declared before the operator setInterval

+2


source


The two pieces of code are not equivalent: in the first, you are passing a reference to an unnamed function to the setInterval function. In the second snippet, you call drawGraph () and then you pass the result value to setInterval.

Try:



var interval = setInterval(drawGraph, 1000);

      

and move the definition of drawGraph before calling setInterval.

+2


source







All Articles