简体   繁体   中英

JavaScript in a web browser: Can I make it event driven instead of looping?

I am working on a robotics project where I control a robot using a joystick and the keys on my keyboard via a browser and a web server on the robot.

Right now the basic (browser side) implementation is a series of functional blocks that read the position of the joystick, the state of the joystick's buttons, and if certain keys have been pressed, sending this information to the server on the robot, using "requestAnimationFrame" as the looping mechanism.

The problem I am experiencing is that the connection between the browser and the robot is too "chatty" - there being updates almost continuously, even if nothing is happening.

Because of this, if I want to watch for a specific behavior on the server side, I cannot because the one useful message is swamped in (literally) thousands of "nothing happened." messages.

The big problem here is the joystick itself as, as far as I know, there are two and only two events - connected and disconnected. Once the joystick status is "connected" the browser sends zillions of messages.

I tried using the timer object in the joystick API data structure as a way of creating a "something happened" event

Viz.:

function is_something_happening(jsdata, gopigo3_joystick) {
  var old_time = gopigo3_joystick.time_stamp
  while (old_time == Number.parseFloat(jsdata.timestamp).toFixed()) {
    ;  // null statement so that this just spins. . . .
    return;
  }
}

What that does is cause the browser to freeze until the next joystick event happens.

Is there some way to program this so that nothing happens until I do something?

Something like a "you go do whatever you want, and when I need you I'll call you" kind of an interrupt or event driven thing - especially for the joystick?

Or, perhaps, there's a better way of debugging and/or trying to track specific events than the brute-force methods I'm using?

I hope that window.addEventListener works for you:

function doTheMovement(){
    //your code
    window.requestAnimationFram(doTheMovement)
}
window.addEventListener('keydown', function(event){
    if(event.keyCode === "YOUR KEYCODE"){
         //change direction of motion
    }
})

window.addEventListener only goes 60 times per second, so it should be less damaging to your computer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM