Background information: I am trying to make an application with ElectronJS. The backend is a python webserver which starts at the same time electron starts.
I will refer to the python webserver as "the backend" and ElectronJS as "the frontend".
Problem: The animation frame needs to execute a callback to the python webserver which executes a system process. At this time the gamepad button is registered multiple times and executes the request to the backend many times.
Desired behavior: What i want is the requestanimationframe not to respond to consecutive keypresses from the gamepad until the function has finished.
What i have tried: Below i have two of the code samples i have tried. There are many more which i have tried, but do not remember. Does anyone have a solution to my problem as described, or a way to get the desired behavior?
Code samples of my attempts
var respondToButton = true;
function scanInput()
{
var gp = false;
if (navigator.getGamepads()[0]) {
gp = navigator.getGamepads()[0];
if (respondToButton){
if(gp.buttons[14].pressed) {
respondToButton = false;
control.next(1)
respondToButton = true;
};
}
}
}
window.requestAnimationFrame(scanInput);
Second try
var animationFrameID;
function scanInput()
{
var gp = false;
if (navigator.getGamepads()[0]) {
gp = navigator.getGamepads()[0];
if(gp.buttons[14].pressed) {
cancelAnimationFrame(animationFrameID);
control.next(1)
animationFrameID = window.requestAnimationFrame(scanInput);
};
}
}
window.requestAnimationFrame(scanInput);
Edit At this moment i am looking at javascript promises, but i cannot seem to grasp the concept properly. What is the simplest form of a promise? I see many different implementations around the web.
Edit 1 Tried a new way with promises, but this also does not provide the preferred behavior.
function scanInput() {
if (navigator.getGamepads()[0]) {
var gp = navigator.getGamepads()[0];
switch(true){
case gp.buttons[0].pressed:
var promise = new Promise(function(resolve, reject){
resolve(control.enter());
});
promise.then(function(result){
window.requestAnimationFrame(scanInput);
});
break;
case gp.buttons[1].pressed:
var promise = new Promise(function(resolve, reject){
resolve(control.back());
});
promise.then(function(result){
window.requestAnimationFrame(scanInput);
});
break;
case gp.buttons[13].pressed:
var promise = new Promise(function(resolve, reject){
resolve(control.prev(1));
});
promise.then(function(result){
window.requestAnimationFrame(scanInput);
});
break;
case gp.buttons[14].pressed:
var promise = new Promise(function(resolve, reject){
resolve(control.next(1));
});
promise.then(function(result){
window.requestAnimationFrame(scanInput);
});
break;
default:
window.requestAnimationFrame(scanInput);
break;
}
}
};
window.requestAnimationFrame(scanInput);