Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't access element from a named javascript function

I have a javascript function, that works fine if it's anonymous but stops working when I change it to named.. 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 does not 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 get the 'Uncaught TypeError: Cannot call method 'update' of undefined'. The strangest part is that I can see that the Processing.js window is getting drawn on screen but that's it.. With the working version (the first one in this post) everything is fine and contents of the window also get drawn..

I tried putting pjs into a global variable outside of drawGraph() function, but no luck... What am I missing? Thanks!

like image 960
Stpn Avatar asked Jul 31 '26 16:07

Stpn


2 Answers

It should be

setInterval(drawGraph,1000);

not

setInterval(drawGraph(),1000);

Also the function should be declared before the setInterval statement

like image 119
Eugene Retunsky Avatar answered Aug 03 '26 06:08

Eugene Retunsky


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

Try with:

var interval = setInterval(drawGraph, 1000);

and move the definition of drawGraph before the call to setInterval.

like image 26
dvd Avatar answered Aug 03 '26 05:08

dvd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!