Encountering an ongoing problem with trial repetition in JsPsych, which is causing the looping to continue endlessly without

As a beginner in JsPsych, I'm diving into creating a basic math quiz task to sharpen my skills. The goal is to generate random math questions as prompts and stop the task after 10 correct answers. I've managed to code that selects random math problems and loops successfully. However, I'm facing a challenge pinpointing the error location, which could be

  1. where correct answers are defined
  2. where correct answers are counted
  3. where question looping occurs

Below is my code. Do let me know if any clarification is needed. Thank you in advance! Edit: I'm including another attempt with different code but same issue


<!DOCTYPE html>
<html>
  <head> <!-- all preloads go into head -->
    <title>Math Quiz</title>
    <!-- any plugins go here-->
    <script src="jspsych/dist/jspsych.js"></script>
    <script src = "jspsych/dist/plugin-survey-text.js"></script>
    <link href="jspsych/dist/jspsych.css" rel="stylesheet" type="text/css" />
  </head>
  <body> <!-- all script for tasks go into body-->
    <script> 
    
    var jsPsych = initJsPsych();

    var timeline = [];

// create a randomly selected math problem prompt and define correct answer
var test = {
    type: jsPsychSurveyText,
    questions: [
        {
            prompt: function() {
                var MathQuest = [

                '2+2', '3+7', 'How many weeks in a year?'

                ];

                var mathProblems = jsPsych.randomization.sampleWithReplacement(MathQuest, 1)[0];
                return mathProblems;
            },
            name: 'resp',
        }
    ],
    post_trial_gap: 500,
    on_finish: function(data) {
        var correctResponses = {

        '2+2' : '4',
        '3+7' : '10',
        'How many weeks in a year?' : '52'
        };

        var response = data.response;

        if (correctResponses[data.prompt] === response) {

            data.correct = true;

        } else {

            data.correct = false;

        }
    }
}; // end test trial

 // Create a loop node for the test with accuracy criteria:
 var correctCount = 0; // Counter for correct responses

      var loopNode = {
        timeline: [test],
        loop_function: function(data) {
          // Check if the loop should continue based on the number of correct responses
          if (correctCount < 10) {
            if (data.values()[0].correct) {
              correctCount++;
            }
            return true; // Continue the loop
          } else {
            return false; // End the loop
          }
          console.log("Correct Count: " + correctCount);
        },
      };

    jsPsych.run([loopNode]);

    </script>
    </body>
    </html>

2nd attempt:

<!DOCTYPE html>
<html>
  <head> <!-- all preloads go into head -->
    <title>Math Quiz Take 2</title>
    <!-- any plugins go here-->
    <script src="jspsych/dist/jspsych.js"></script>
    <script src = "jspsych/dist/plugin-survey-text.js"></script>
    <link href="jspsych/dist/jspsych.css" rel="stylesheet" type="text/css" />
  </head>
  <body> <!-- all script for tasks go into body-->
    <script> 

var jsPsych = initJsPsych();

var timeline = [];

var mathQuestions = [
  {math: '2+2 = ?', correct: '4'},
  {math: '2x3 = ?', correct: '6'},
  {math: '5x7 = ?', correct: '35'}
];

var test = {
  type: jsPsychSurveyText,
  questions: [
    {
      prompt: jsPsych.timelineVariable('math'), 
      name: 'resp'
    }
  ],
        on_finish: function(data) {
                  data.correct=jsPsych.timelineVariable('correct');
                  var acc = 0;
                  var response = data.response.resp;
            if (response == data.correct){
                acc++;
            }
          }
};

var mathQuestionProcedure = {
  timeline: [test],
  timeline_variables: mathQuestions,
  loop_function: function(data) {
    if (acc < 2) {
            return true; //go to criteria
        } else {
            return false; //end loop
        }
  }
}
timeline.push(mathQuestionProcedure);

jsPsych.run([mathQuestionProcedure])

</script>
</body>
</html>

Answer №1

To me, the second try seems more accurate. It appears that the issue stems from initializing var acc = 0 within the on_finish function, causing it to be limited in scope. To rectify this, consider placing var acc = 0 before creating the test object and removing it from the function. This adjustment will transform it into a global variable, potentially resolving the issue.

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

What is the best way to ensure that this encompassing div adjusts its width to match that of its child elements?

My goal is to keep fave_hold at 100% of its parent div, while limiting the width of .faves to fit its child elements. These elements are generated dynamically with predefined widths. Below is the code snippet in React/JSX format: <div id='fave_h ...

Encountering silence: React JS fetch call left unanswered by Sinatra server

Exploring the realms of Sinatra and React JS, I am venturing into making a GET call from my React website to a Sinatra server in order to display plain text. The Sinatra Server script: require 'sinatra' set :root, 'lib/app' before d ...

Create an input field dynamically by utilizing the append method in jQuery

Concern: As part of an edit page, I am working on appending an input field from a modal window to an existing panel while retaining the format of the rest of the fields. The user is currently able to create and add the new field using the code provided in ...

Issue with Jquery event not triggering correctly following ajax data retrieval

This script uses jQuery and Ajax to populate a navigation bar with categories and subcategories dynamically. The first unordered list is static, while the second one is populated after receiving data via Ajax. There are some jQuery events that need to be i ...

Efficiently run multiple Node-written apps on a single server

I currently have a single VPS and would like to host multiple node.js apps on it, similar to how Apache or Nginx works. I am using Nginx as a proxy, but I have concerns. As you know, one of the key features of Node.js is its non-blocking I/O and sing ...

Node.Js error: "The requested resource does not have the 'Access-Control-Allow-Origin' header present."

This particular query shares similarities with others, however there is a perplexing difference that is causing it to malfunction. Previously, my JavaScript was able to fetch 6 json files without any issues. In Node.JS, I have configured cors and headers ...

Displaying Well-Formatted XML in Angular2 Using Typescript

After receiving this XML string from the server: <find-item-command xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" find-method="Criteria" item-class="com" only-id="false" xsi:schemaLocation=""> <criteria> <criterion> <descripto ...

The "angular2-image-upload" npm package encountering a CORS issue

Using the angular2-image-upload library for uploading files has been a smooth process until recently. After upgrading from version 0.6.6 to 1.0.0-rc.1 to access new features in future, I encountered issues with image uploads. The errors I faced were: htt ...

Ever wonder what goes on behind the scenes when you press a button before the Javascript method is carried out

My web application is built using ASP.NET MVC 4, jQuery, and Telerik's Kendo controls. Within my webpage, I have the following code snippet: <input id="cmdSaveToFile" title="Save To File" class="button" type="button" value="Save To File" onclick= ...

Setting configuration files in Node.js with npm configuration

I have developed a SAAS application on the Angular/NodeJS/Postgres+MongoDB stack that can establish connections with customer databases, cloud warehouses, S3 buckets, and more to load relevant information. Once I receive connection details from the Angular ...

Activate JavaScript functions by pressing the enter key, allowing for various searches, AJAX requests, and DataTable displays to occur seamlessly without the need to refresh

I recently developed a web page that integrates an AWS API interface to interact with an RDS Aurora MySQL Serverless database. Users can input a SQL statement and click the Query button, which triggers an AJAX request, returns JSON data, and converts the d ...

What is the procedure for altering the location of a mesh within the animate() function in three.js?

In my implementation of a three.js mesh (found in three.js-master\examples\webgl_loader_collada_keyframe.html), I have a basic setup: function init() { ... ... var sphereGeometry = new THREE.SphereGeometry( 50, 32, 16 ); var sphereMater ...

The dependency path in the package.json file contains all the necessary files

I recently developed a JavaScript package and here is the configuration in my package.json: { "name": "packageName", "version": "1.0.0", "description": "Description of the package", " ...

Steps for executing a Node script are as follows:

My task is to execute a node script that will remove an object from an external API. This can be achieved by running the following command: node server.js Customer55555 Upon execution, the specified object should be deleted successfully. To interact wit ...

What is causing the #reset button to trigger the Flow.reset() function when the #gameboard does not contain any child elements?

Whenever I click on the resetBtn, it triggers the Flow.reset function regardless of whether the gameboard has child elements. Am I using the hasChildNodes() method incorrectly? const resetBtn = document.querySelector('#reset'); resetBtn.addEventL ...

Working with scrollIntoView in useEffect (Encountering an error trying to access 'scrollIntoView' property of null)

Starting from scratch, I'm working on setting up my webpage and crafting some code. function BasicDetails() { React.useEffect(()=>{ scrollView(); }, []); function scrollView() { document.getElementById('main-root& ...

The dropdown menu is not able to retrieve information from the secondary database

I have been encountering multiple challenges while working on a web-based dynamic form that I am developing. My current major issue is with populating the second #bodytype dropdown based on the selection made in the first, #bodyman, dropdown. Subsequently ...

Ways to extract the ASP.net variable value and place it inside a JavaScript textbox

Currently, I'm in the process of developing Javascript code for an ASP.net page. Within my coding framework, the string "foo" is linked to a string variable called myString. In order to transfer the value of myString to a JavaScript variable, I incl ...

"Prevent further button clicks by disabling it after the initial click with ActionRowBuilder in Discord.Js

Encountering a puzzling issue where I am unable to disable a button after it has been clicked. The option to disable the button does not seem to appear. When attempting to deactivate the button, I utilize the following function: const row = new ActionRowBu ...

Creating a hash from a string in Javascript

I'm struggling with the process of converting a string into a nested hash in JavaScript. Here is the string I want to convert: "{'btc_usd': {'price': 376.2, 'volume': 42812.69, 'change': -0.5},'btc_cn ...