JavaScript Callback. (solved)

A5e1688390feaaa879805a8b39c32194
0
Schoening 101 Oct 29, 2012 at 20:02

I have read a few articles about it, but I still don’t understand callback correctly I think.
Most articles make it sound likereturn.

Essentially what I want to do is run Callback functions on my Server to ensure max speed of the processes.

setTimeout and setInterval can be troublesome. And after asking on StackOverflow, they referred me to callback.

I would like a brief explanation perhaps.
Or tell me if I am right in that callback basically runs as fast as it can. Keeping in mind that JavaScript is event-based and asynchronous.

Here is a piece of JavaScript that is not working, perhaps someone can fix it and explain my error.

function test(callback)
{

if (cubePos < 5)
  {
  cube.position.x = cube.position.x + 0.1;
  cubePos = cube.position.x;
  }

  else
  {
   cube.position.x = - 5;
   cubePos = cube.position.x;
  }

    callback.call(test());

  };

It looks like I am calling the function within itself. But I don’t know how it is supposed to look with callback.

4 Replies

Please log in or register to post a reply.

A5e1688390feaaa879805a8b39c32194
0
Schoening 101 Oct 29, 2012 at 20:13

I though a little about this.. I could just run a continuous while loop on the server I guess.

A8433b04cb41dd57113740b779f61acb
0
Reedbeta 167 Oct 29, 2012 at 20:45

I’m confused. Is all this Javascript code running on the server, using node.js or suchlike? Javascript is usually a client-side language.

6837d514b487de395be51432d9cdd078
0
TheNut 179 Oct 29, 2012 at 21:46

The purpose of a callback is to execute another function. In your case, you are recursively calling the test() function as an argument to the callback function, which will obviously lead into a stack overflow and deadlock the app. The whole point of the callback variable is to do something like this:

function test (call_me_back)
{
call_me_back();
// or
call_me_back.call("arg1", "arg2"); //<-- call_me_back function has "this" instance as "owner"
// or
call_me_back.apply(this, "arg1", "arg2"); // <-- Like call() but you can specify the owner.
}

// This is equivalent to what your code does
function test ()
{
     test();
}

If I were to wager a guess, it looks like you want to create a runtime loop. If you’re writing HTML5 compliant code, you should look into window.requestAnimationFrame (API varies on browser - hooray for standards!). If the browser doesn’t support that, then setTimeout really is your next best option.

If this is about Node.js, then I have no idea. IMO write a server using a real language :) (/troll).

A5e1688390feaaa879805a8b39c32194
0
Schoening 101 Oct 29, 2012 at 21:59

@TheNut

If this is about Node.js, then I have no idea. IMO write a server using a real language :) (/troll).

Haha!

Thanks for the help.

The server runs on NodeJS indeed ;)

I think I have simply read more about JavaScript loops. And general Game AI loops.