# 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 ```javascript // 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 ```javascript 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 ```javascript // 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.clearAllTimeouts ``` jsPsych.pluginAPI.clearAllTimeouts() ``` ### Parameters None. ### Return value Returns nothing. ### Description Clears any pending timeouts that were set using jsPsych.pluginAPI.setTimeout() --- ## jsPsych.pluginAPI.compareKeys ``` jsPsych.pluginAPI.compareKeys(key1, key2) ``` ### Parameters Parameter | Type | Description ----------|------|------------ key1 | string or numeric | The representation of a key, either string or keycode key2 | string or numeric | The representation of a key, either string or keycode ### Return value Returns true if keycodes or strings refer to the same key, regardless of type. ### Description Compares two keys to see if they are the same, ignoring differences in representational type. ### Examples ```javascript jsPsych.pluginAPI.compareKeys('a', 65); // returns true jsPsych.pluginAPI.convertKeyCharacterToKeyCode('space', 31) // returns false ``` --- ## 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 ```javascript var keycode = jsPsych.pluginAPI.convertKeyCharacterToKeyCode('a') // keycode is 65 keycode = jsPsych.pluginAPI.convertKeyCharacterToKeyCode('space') // keycode is 32 ``` --- ## jsPsych.pluginAPI.convertKeyCodeToKeyCharacter ``` jsPsych.pluginAPI.convertKeyCodeToKeyCharacter(character) ``` ### Parameters Parameter | Type | Description ----------|------|------------ code | numeric | The numeric representation of keyboard key. ### Return value Returns the string representation of the key associated with the `code` parameter. ### Description Converts between the numeric key code of a key and the string representation associated with that key. ### Examples ```javascript var keycode = jsPsych.pluginAPI.convertKeyCharacterToKeyCode(65) // key is 'a' keycode = jsPsych.pluginAPI.convertKeyCharacterToKeyCode(32) // keycode is 'space' ``` --- ## 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 buffered audio file for playback. If the browser supports it the buffer will be playable with the WebAudio API. Otherwise, the returned buffer will be an HTML5 Audio object. ### Description Gets an AudioBuffer that can be played with the WebAudio API or an Audio object that can be played with HTML5 Audio. The file must be preloaded with `preloadAudioFiles` or the automatic preload (`autoPreload`). ### Examples ```javascript // the code below is used to play audio in the audio-keyboard-response plugin var source = context.createBufferSource(); source.buffer = jsPsych.pluginAPI.getAudioBuffer(trial.stimulus); source.connect(context.destination); startTime = context.currentTime; 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](http://caniuse.com/#search=performance), 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 ```javascript 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 ```javascript 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.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](../overview/media-preloading.md) 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 ```javascript var sounds = ['file1.mp3', 'file2.mp3', 'file3.mp3']; jsPsych.pluginAPI.preloadAudioFiles(sounds, function(){ startExperiment(); }); function startExperiment(){ jsPsych.init({ timeline: exp }); } ``` #### Show progress of loading ```javascript var sounds = ['file1.mp3', 'file2.mp3', 'file3.mp3']; jsPsych.pluginAPI.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](../overview/media-preloading.md) 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 ```javascript var images = ['img/file1.png', 'img/file2.png', 'img/file3.png']; jsPsych.pluginAPI.preloadImages(images, function(){ startExperiment(); }); function startExperiment(){ jsPsych.init({ timeline: exp }); } ``` #### Show progress of loading ```javascript var images = ['img/file1.png', 'img/file2.png', 'img/file3.png']; jsPsych.pluginAPI.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, conditional_function) ``` ### Parameters Parameter | Type | Description ----------|------|------------ plugin_name | string | The name of the plugin. e.g., 'image-keyboard-response'. 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'. conditional_function | function | Only run the preload for a trial if this function returns true, or if this function does not exist. ### 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. The `conditional_function` function is passed a single argument containing the trial object. ### Example For an example, see the [image-keyboard-response](https://github.com/jodeleeuw/jsPsych/blob/master/plugins/jspsych-image-keyboard-response.js) and [audio-keyboard-response](https://github.com/jodeleeuw/jsPsych/blob/master/plugins/jspsych-audio-keyboard-response.js) plugins. --- ## jsPsych.pluginAPI.setTimeout ``` jsPsych.pluginAPI.setTimeout(callback, delay) ``` ### Parameters Parameter | Type | Description ----------|------|------------ callback | function | A function to execute after waiting for delay. delay | integer | Time to wait in milliseconds. ### Return value Returns the ID of the setTimeout handle. ### Description This is simply a call to the standard setTimeout function in JavaScript with the added benefit of registering the setTimeout call in a central list. This is useful for scenarios where some other event (the trial ending, aborting the experiment) should stop the execution of queued timeouts. ### Examples ```javascript // print the time console.log(Date.now()) // print the time 1s later jsPsych.pluginAPI.setTimeout(function(){ console.log(Date.now()) }, 1000); ```