Event-related callback functions

jsPsych offers the ability to call arbitrary functions in response to certain events occurring, like the end of a trial or when new data is saved. This page summarizes the different opportunities for callback functions and how to specify them.


on_data_update

The on_data_update callback can be declared in the jsPsych.init method. The callback triggers whenever data is generated by a plugin (specifically, whenever the jsPsych.data.write method is called). The function will be passed a single argument, which contains the data that was written.

Sample use

jsPsych.init({
  timeline: exp,
  on_data_update: function(data) {
    console.log('Just added new data. The contents of the data are: '+JSON.stringify(data));
  }
});

on_finish (trial)

The on_finish callback can be added to any trial. The callback will trigger whenever the trial ends. The callback function will be passed a single argument, containing the data object from the trial.

Sample use

var trial = {
  type: 'single-stim',
  stimulus: 'imgA.png',
  on_finish: function(data) {
    console.log('The trial just ended.');
    console.log(JSON.stringify(data));
  }
};

on_finish (experiment)

The on_finish callback can be declared in the jsPsych.init method. The callback will trigger once all trials in the experiment have been run. The method will be passed a single argument, containing all of the data generated in the experiment.

Sample use

jsPsych.init({
  timeline: exp,
  on_finish: function(data) {
    console.log('The experiment is over! Here is all the data: '+JSON.stringify(data));
  }
});

on_trial_finish

The on_trial_finish callback can be declared in the jsPsych.init method. The callback will trigger at the end of every trial in the experiment. If you want a callback to trigger only for the end of certain trials, use the on_finish callback on the trial object. There are no parameters passed to the callback function.

Sample use

jsPsych.init({
  timeline: exp,
  on_trial_finish: function() {
    console.log('A trial just ended.');
  }
});

on_trial_start

The on_trial_start callback can be declared in the jsPsych.init method. The callback will trigger at the start of every trial in the experiment. There are no parameters passed to the callback function.

Sample use

jsPsych.init({
  timeline: exp,
  on_trial_start: function() {
    console.log('A trial just started.');
  }
});