Struggling to manage the flow of my program, constantly switching back and forth between handling AJAX callbacks and rendering PIXI

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?

Answer №1

When it comes to function naming and responsibilities, there are a few key points to keep in mind. Firstly, if your function has a generic name with a different comment above it, consider renaming the function and removing the comment. Secondly, ensure that your function only performs the task it is named for, without any extra actions. Lastly, avoid modifying the parent scope within your function as side effects can complicate debugging.

With those guidelines in mind, let's break down the code into smaller functions that have clear and specific purposes. By creating these precise functions, we can minimize the chances of errors occurring.

//Initialize PIXI
var stage = new PIXI.Stage(0x000000);
var renderer = new PIXI.WebGLRenderer(1600, 900);
document.body.appendChild(renderer.view);

function httpRequest(method, url, success, fail) {
  var xmlhttp = new XMLHttpRequest();

  xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == 4 ) {
      if(xmlhttp.status == 200){
        success(xmlhttp.responseText);
      }
      else {
        fail();
      }
    }
  }

  xmlhttp.open(method, url, true);
  xmlhttp.send();
}

function getRequest(url, success, fail) {
  httpRequest('GET', url, success, fail);
}

function postRequest(url, success, fail) {
  httpRequest('POST', url, success, fail);
}

function buildDataStringFromCoords(coords) {
  return coords.map(function(coord) {
    return coord.x.toString() + ',' + coord.y.toString();
  }).join('C');
}

function buildCoordsFromDataString(dataString) {
  return dataString.split('C').map(function(coordString) {
    var points = coordString.split(',');
    return {x:+points[0], y:+points[1]};
  });
}

function renderCoords(coords) {
  var graphics = new PIXI.Graphics(); //Creating new graphics every time due to PixiJS bug.
  graphics.lineStyle(1, 0xFFFFFF);
  stage.addChild(graphics);
  graphics.drawRect(coords.x, coords.y, 1, 1);
  renderer.render(stage);
}

function requestCoords(indx, success, fail) {
  var url = 'http://127.0.0.1/receiveData/0=' + indx;
  getRequest(
    url, 
    function(response) {
      var coords = buildCoordsFromDataString(response);
      success(coords);
    },
    function() {
      fail();
    }
  );
}

var sendCoords = function(coords, success, fail) {
  var url = 'http://127.0.0.1/sendData/' + buildDataStringFromCoords(coords);
  postRequest(
    url,
    function() {
      success();
    },
    function() {
      fail();
    }
  );
}

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('Mouse moved', p.x, p.y);
}, false);

var interval = setInterval(function(){
  console.log("Make Request.");
  sendCoords(
    mouseRecording,
    function() {
      console.log('Successfully sent coords', mouseRecording);
    },
    function() {
      console.log('Failed to send coords', mouseRecording);
    }
  );
  requestCoords(
    indx,
    function(coords) {
      console.log('Successfully fetched coords', coords);
      coords.forEach(function(coord) {
        renderCoords(coord);
      });
      console.log('Rendered coords', indx);
    },
    function() {
      console.log('Failed to get coords', indx);
    }
  );
}, 100);

By breaking down the code into smaller, focused functions, we can create tests to verify the correctness of each part individually. This approach can streamline the debugging process and make issues more transparent.

function testBuildDataStringFromCoords() {
  return buildDataStringFromCoords([{x:123,y:456},{x:987,y:654}]) === '123,456C987,654';
}

While this restructuring may not resolve all your challenges, it aims to simplify your workflow and shed light on potential problems for a smoother development experience.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Enhancing User Authentication with Firebase Email Verification in React Native

Does Firebase have a feature that allows me to verify if an email confirmation has already been sent to a user? I am able to check validation, but I need to determine whether the verification email has already been sent in order to decide if it needs to be ...

how to create a smooth transition back to the original state after a click event

I've put in a lot of effort to make sure my code for the DECAY shapes is correct up to this point. The click event I implemented makes the shapes gradually start being affected, just as I intended. However, once I release the mouse or finger, it insta ...

Using Javascript or jQuery, focus on a div containing a paragraph element with a particular text

I've been struggling for hours trying to figure out how to select a div that contains a specific p element. HTML <div class="NavBar_Row_Button2"><p>DONATE</p></div> <div class="NavBar_Row_Button2"><p>CONTACT</p ...

Can qTip 2.0 be configured to use a different default attribute instead of 'title'?

Is there a way to set qTip to use an attribute other than 'title' as the default? I need to use another attribute because when I disable qtip and add elements dynamically with "title", the title still shows when I hover over the element, which i ...

React Module cannot be found: Error: Unable to locate - import paths

New to coding and currently working on a website using React. Encountering three errors persistently: ERROR in ./src/Components/Pages1/Home.js 6:0-50 Module not found: Error: Can't resolve './Components/Cards/Cards1.js' in 'C:\Use ...

Transferring PHP variables to a JavaScript function through AJAX requests and displaying the response text on the current page

I have implemented php sql database connectivity on a php page called search.php in order to retrieve data from a database and store it in a variable "$url". This variable is then passed to a javascript function via ajax calls, which further transmits it t ...

Update the observability status of one observable using a different observable

Upon running the following code, you'll notice that an xhr request is being sent to the console regardless of whether I am subscribed to the subject or not. I would prefer for these requests not to be made if I am not subscribed. // To start, install ...

Encountering difficulties in constructing next.js version 14.1.0

When attempting to build my next.js application, I use the command npm run build Upon running this command, I encountered several errorshttps://i.sstatic.net/5jezCKHO.png Do I need to address each warning individually or is there a way to bypass them? B ...

Leveraging form.errors.as_json for enhanced parsing to generate HTTP responses in Django

As someone who is relatively new to both JSON and Django forms, I find myself wondering about the proper way to utilize Djagno's user_form.errors.as_json() function for transferring error messages to the client-side. Currently, my code looks like this ...

Separate the information into different sets in JavaScript when there are more than two elements

Upon extraction, I have obtained the following data: ╔════╦══════════════╦ ║ id ║ group_concat ║ ╠════╬══════════════╬ ║ 2 ║ a ║ ║ 3 ║ a,a ...

What causes a significant influx of packages each time I execute the command `npm install`?

https://i.sstatic.net/a3BxV.png https://i.sstatic.net/dcVXS.png Could this be related to my overall package.json file? ...

Error in Typescript for a function that accepts several types of lists - property does not exist on the interface

In my project, I have defined three interfaces: a base interface and two others that extend the base one with children as properties. One of the interfaces includes 'valueType' while the other includes 'returnType'. Here is how they are ...

A JavaScript syntax problem arises when attempting to fetch data (an object) from a Laravel controller

Encountering a JavaScript syntax error in my .blade.php file when trying to access $data->modal This is my controller function: public function buku_all($page, $modal) {$data = (object) [ 'sidebar' => "pelayanan", ...

Incorporate a 1-second delay for each value in the stream using Bacon.js

Here is my code snippet: var bulk = array[1,2,3,4] var finalResult = Bacon .fromArray(bulk) .flatMap(isValInCouchDb) .filter(onesThatExist) .flatMap(putValInCouchDb) I want to introduce a 1-second delay after the filter operation before e ...

Exploring the concepts of angularjs $apply and $scope within the context of object manipulation

In nearly every software application, there is a necessity to modify objects. In my scenario, I have a list of objects that can be edited on the fly with the help of Angular. However, this leads to a dilemma as exemplified by the following controller: ...

Utilizing variables as identifiers in React Native programming

Trying to utilize a dynamic name for a property of an object. For instance, within the function provided below, aiming to use the value stored in the variable 'catagoryId' to access the corresponding child element and assign it to the variable c ...

Struggling to achieve improved results with Ambient Occlusion in three.js

After reviewing the demonstration here . var depthShader = THREE.ShaderLib[ "depthRGBA" ]; var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms ); depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vert ...

Tips for implementing a handler on a DOM element

$(document).ready(function(){ var ColorBars = document.getElementsByClassName("color-bar"); var number = 0; ColorBars[0].onclick = hideLine(0); function hideLine(index){ var charts = $("#line-container").highcharts(); v ...

Currently, I am working on a project and encountering an issue with html2canvas

const handleDownloadImage = async () => { try { const canvas = await html2canvas(cardRef.current); console.log(cardRef.current); const imageData = canvas.toDataURL("image/png"); setImageUrl(imageData); } catch ( ...

Error: Unable to access 'author' property as it is undefined

Currently, I am in the process of learning how to create my own blog by following a tutorial on Github. The tutorial can be found at https://github.com/adrianhajdin/project_graphql_blog. However, while working with [slug].js to build localhost/3000/post/re ...