jsPsych.pluginAPI

The pluginAPI module contains functions that are useful when developing new plugins.


jsPsych.pluginAPI.autoPreload

jsPsych.pluginAPI.autoPreload(timeline, callback)

Parameters

Parameter Type Description
timeline TimelineNode object A TimelineNode object that contains an arbitrary set of trials.
callback function A function to execute when loading is complete

Return value

Returns nothing.

Description

Attempts to preload all image files and audio files that will be used to run the trials on the timeline. Content will only preload from plugins that have used the registerPreload method to define the media types of their parameters.

The callback function executes once all of the files are preloaded.

This method is used internally by the core jsPsych code. It is not recommended that you call it manually.

Examples

// you probably shouldn't use this method

jsPsych.pluginAPI.cancelAllKeyboardResponses

jsPsych.pluginAPI.cancelAllKeyboardResponses()

Parameters

None.

Return value

Returns nothing.

Description

Cancels all currently active keyboard listeners created by jsPsych.pluginAPI.getKeyboardResponse.

Examples

jsPsych.pluginAPI.cancelAllKeyboardResponses();

jsPsych.pluginAPI.cancelKeyboardResponse

jsPsych.pluginAPI.cancelKeyboardResponse(listener_id)

Parameters

Parameter Type Description
listener_id object The listener_id object generated by the call to jsPsych.pluginAPI.getKeyboardResponse.

Return value

Returns nothing.

Description

Cancels a specific keyboard listener created by jsPsych.pluginAPI.getKeyboardResponse.

Examples

// create a persistent keyboard listener
var listener_id = jsPsych.pluginAPI.getKeyboardResponse(after_response, ['p','q'], 'date', true);

// cancel keyboard listener
jsPsych.pluginAPI.cancelKeyboardResponse(listener_id);

jsPsych.pluginAPI.convertKeyCharacterToKeyCode

jsPsych.pluginAPI.convertKeyCharacterToKeyCode(character)

Parameters

Parameter Type Description
character string The string representation of keyboard key.

Return value

Returns the numeric keycode associated with the character parameter.

Description

Converts between the string representation of a key and the numeric key code associated with that key.

Examples

var keycode = jsPsych.pluginAPI.convertKeyCharacterToKeyCode('a')
// keycode is 65

keycode = jsPsych.pluginAPI.convertKeyCharacterToKeyCode('space')
// keycode is 32

jsPsych.pluginAPI.getAudioBuffer

jsPsych.pluginAPI.getAudioBuffer(filepath)

Parameters

Parameter Type Description
filepath string The path to the audio file that was preloaded.

Return value

Returns an audio buffer compatible with the WebAudio API for the given filepath.

Description

Gets an AudioBuffer that can be played with the WebAudio API. The file must be preloaded with preloadAudioFiles or the automatic preload (autoPreload).

Examples

// the code below is used to play audio in the single-audio plugin
var source = context.createBufferSource();
source.buffer = jsPsych.pluginAPI.getAudioBuffer(trial.stimulus);
source.connect(context.destination);
startTime = context.currentTime + 0.1;
source.start(startTime);

jsPsych.pluginAPI.getKeyboardResponse

jsPsych.pluginAPI.getKeyboardResponse(parameters)

Parameters

The method accepts an object of parameter values (see example below). The valid keys for this object are listed in the table below.

Parameter Type Description
callback_function function The function to execute whenever a valid keyboard response is generated.
valid_responses array An array of key codes or character strings representing valid responses. Responses not on the list will be ignored. An empty array indicates that all responses are acceptable.
rt_method string Indicates which method of recording time to use. The 'date' method uses calls to (new Date()).getTime() to record timing information. The 'performance' method uses calls to performance.now(), which is a more modern JavaScript feature. The 'performance' approach is not supported by all the major browsers yet, but adoption rates are increasing. The audio method is used in conjuction with an audio_context (set as an additional parameter). This uses the clock time of the audio_context when audio stimuli are being played.
audio_context AudioContext object The AudioContext of the audio file that is being played.
audio_context_start_time numeric The scheduled time of the sound file in the AudioContext. This will be used as the start time.
allow_held_key boolean If true, then responses will be registered from keys that are being held down. If false, then a held key can only register a response the first time that getKeyboardResponse is called for that key. For example, if a participant holds down the A key before the experiment starts, then the first time getKeyboardResponse is called, the A will register as a key press. However, any future calls to getKeyboardResponse will not register the A until the participant releases the key and presses it again.
persist boolean If false, then the keyboard listener will only trigger the first time a valid key is pressed. If true, then it will trigger every time a valid key is pressed until it is explicitly cancelled by jsPsych.pluginAPI.cancelKeyboardResponse or jsPsych.pluginAPI.cancelAllKeyboardResponses.

Return value

Return an object that uniquely identifies the keyboard listener. This object can be passed to jsPsych.pluginAPI.cancelKeyboardResponse to cancel the keyboard listener.

Description

Gets a keyboard response from the subject, recording the response time from when the function is first called until a valid response is generated.

A valid response triggers the callback_function specified in the parameters. A single argument is passed to the callback function. The argument contains an object with the properties key and rt. key contains the numeric key code of the response, and rt contains the response time.

Examples

Get a single response from any key


var after_response = function(info){
    alert('You pressed key '+info.key+' after '+info.rt+'ms');
}

jsPsych.pluginAPI.getKeyboardResponse({
  callback_function:after_response,
  valid_responses: [],
  rt_method: 'date',
  persist: false
});

Get a responses from a key until the letter Q is pressed


var after_response = function(info){
    alert('You pressed key '+info.key+' after '+info.rt+'ms');

    if(info.key == 81){ // the key code for 'Q' is 81.
        jsPsych.pluginAPI.cancelKeyboardResponse(listener);
    }
}

var listener = jsPsych.pluginAPI.getKeyboardResponse({
  callback_function:after_response,
  valid_responses: [],
  rt_method: 'date',
  persist: true
});

jsPsych.pluginAPI.evaluateFunctionParameters

jsPsych.pluginAPI.evaluateFunctionParameters(trial, protect)

Parameters

Parameter Type Description
trial object An object representing the trial (typically the same variable that gets passed to the plugin.trial method). It contains key: value pairs describing all the trial parameters.
protect array An array of strings, indicating which parameters in the trial object should be protected from normalization

Return value

Returns a the trial object with all values that were functions replaced by the return value of the function.

Description

This method replaces any parameters that are functions with the output of the function.

Example


// a snippet from a trial method

plugin.trial = function(display_element, trial) {

    trial = jsPsych.pluginAPI.evaluateFunctionParameters(trial);

     // the rest of the trial code...
}


jsPsych.pluginAPI.preloadAudioFiles

jsPsych.pluginAPI.preloadAudioFiles(files, callback_complete, callback_load)

Parameters

Parameter Type Description
files array An array of audio file paths to load. The array can be nested (e.g. if images are in multiple arrays to help sort by condition or task).
callback_complete function A function to execute when all the files have been loaded.
callback_load function A function to execute after each file has been loaded. A single parameter is passed to this function which contains the number of files that have been loaded so far.

Return value

Returns nothing.

Description

Use this function to preload audio files that are not part of a plugin with automatic preloading. Audio files in official plugins will automatically preload. See Media Preloading for more information.

It is possible to run this function without specifying a callback function. However, in this case the code will continue executing while the files are loaded. Thus, it is possible that an audio file would be required for playing before it is done preloading. The callback_complete function will only execute after all the audio files are loaded, and can be used to control the flow of the experiment (e.g. by starting the experiment in the callback_complete function).

The callback_load function can be used to indicate progress. See example below.

Examples

Basic use


var sounds = ['file1.mp3', 'file2.mp3', 'file3.mp3'];

jsPsych.preloadAudioFiles(sounds, function(){ startExperiment(); });

function startExperiment(){
    jsPsych.init({
        timeline: exp
    });
}

Show progress of loading

var sounds = ['file1.mp3', 'file2.mp3', 'file3.mp3'];

jsPsych.preloadAudioFiles(sounds, function(){ startExperiment(); }, function(nLoaded) { updateLoadedCount(nLoaded); });

function updateLoadedCount(nLoaded){
    var percentcomplete = nLoaded / sounds.length * 100;

    // could put something fancier here, like a progress bar
    // or updating text in the DOM.
    console.log('Loaded '+percentcomplete+'% of audio files');
}

function startExperiment(){
    jsPsych.init({
        timeline: exp
    });
}

jsPsych.pluginAPI.preloadImages

jsPsych.pluginAPI.preloadImages(images, callback_complete, callback_load)

Parameters

Parameter Type Description
images array An array of image paths to load. The array can be nested (e.g. if images are in multiple arrays to help sort by condition or task).
callback_complete function A function to execute when all the images have been loaded.
callback_load function A function to execute after each image has been loaded. A single parameter is passed to this function which contains the number of images that have been loaded so far.

Return value

Returns nothing.

Description

Use this function to preload image files that are not part of a plugin with automatic preloading. Image files in official plugins will automatically preload. See Media Preloading for more information.

It is possible to run this function without specifying a callback function. However, in this case the code will continue executing while the images are loaded. Thus, it is possible that an image would be required for display before it is done preloading. The callback_complete function will only execute after all the images are loaded, and can be used to control the flow of the experiment (e.g. by starting the experiment in the callback_complete function).

The callback_load function can be used to indicate progress, if the number of images to be loaded is known ahead of time. See example below.

Examples

Basic use


var images = ['img/file1.png', 'img/file2.png', 'img/file3.png'];

jsPsych.preloadImages(images, function(){ startExperiment(); });

function startExperiment(){
    jsPsych.init({
        timeline: exp
    });
}

Show progress of loading

var images = ['img/file1.png', 'img/file2.png', 'img/file3.png'];

jsPsych.preloadImages(images, function(){ startExperiment(); }, function(nLoaded) { updateLoadedCount(nLoaded); });

function updateLoadedCount(nLoaded){
    var percentcomplete = nLoaded / images.length * 100;

    // could put something fancier here, like a progress bar
    // or updating text in the DOM.
    console.log('Loaded '+percentcomplete+'% of images');
}

function startExperiment(){
    jsPsych.init({
        timeline: exp
    });
}

jsPsych.pluginAPI.registerPreload

jsPsych.pluginAPI.registerPreload(plugin_name, parameter, media_type)

Parameters

Parameter Type Description
plugin_name string The name of the plugin. e.g., 'single-stim'.
parameter string The name of the parameter that is a media file. e.g., 'stimulus'
media_type string The type of media, either 'image' or 'audio'.

Return value

Nothing.

Description

Use this method in a plugin file to mark a parameter as containing an element that should be preloaded. The method should be called in the plugin file such that it gets called when the file is loaded.

Example

For an example, see the single-stim and single-audio plugins.