I'm struggling with optimizing the flow of my JavaScript script. The script is responsible for receiving and sending mouse coordinates to be drawn.
Take a look at the code snippet below:
//Initializing PIXI
var stage = new PIXI.Stage(0x000000);
var renderer = new PIXI.WebGLRenderer(1600, 900);
document.body.appendChild(renderer.view);
//animation loop
function animate() {
console.log("Draw.");
requestAnimFrame(animate);
renderer.render(stage);
}
//Function to receive data.
indx = 0;
var makeRequest = function(){
var ajaxFunction = function(){
if(ajaxRequest.readyState == 4){
var pointsStr = ajaxRequest.responseText.split("C");
indx = parseInt(pointsStr[pointsStr.length - 1]);
for (i = 0; i < pointsStr.length - 1; i++) {
if(pointsStr[i] != ""){
var points = pointsStr[i].split(",");
mouseX = parseInt(points[0]);
mouseY = parseInt(points[1]);
var graphics = new PIXI.Graphics();
graphics.lineStyle(1, 0xFFFFFF);
stage.addChild(graphics);
graphics.drawRect(mouseX,mouseY,1,1);
renderer.render(stage);
console.log("Received.")
}
}
}
}
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = ajaxFunction;
ajaxRequest.open("GET", "http://127.0.0.1/receiveData/0=" + indx, true);
ajaxRequest.send();
}
//Function to send data.
var sendRequest = function(arr){
var t = ""
for (var i = 0; i < arr.length; i++) {
t += arr[i].x.toString() + "," + arr[i].y.toString() + "C";
}
t = t.slice(0,-1);
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.open("POST", "http://127.0.0.1/sendData/" + t, true);
ajaxRequest.send();
console.log("Send.")
}
pos = {
x: 0,
y: 0
}
var mouseRecording = new Array();
document.addEventListener('mousemove', function(e){
var p = pos;
p.x = e.clientX || e.pageX;
p.y = e.clientY || e.pageY;
mouseRecording.push(pos);
console.log("" + p.x + "," + p.y)
}, false);
var interval = setInterval(function(){
console.log("Make Request.");
sendRequest(mouseRecording);
makeRequest();
}, 100);
The issue I am facing is the inconsistency in the program's flow.
There are times when it appears to be stuck for 10 seconds without any callbacks being executed, followed by sudden bursts of 200 requests running continuously. Occasionally, the screen rendering would happen randomly as well.
What would be the best approach to ensure smooth execution of the program?