Javascript API

Dallinger provides a javascript API to facilitate creating web-based experiments. All of the dallinger demos use this API to communicate with the experiment server. The API is defined in the dallinger2.js script, which is included in the default experiment templates.

The dallinger object

Any page that includes dallinger2.js script will have a dallinger object added to the window global namespace. This object defines a number of functions for interacting with Dallinger experiments.

Making requests to experiment routes

dallinger provides functions which can be used to asynchronously interact with any of the experiment routes described in Web API:

static dallinger.get(route, data)

Convenience method for making an AJAX GET request to a specified route. Any callbacks provided to the done() method of the returned Deferred object will be passed the JSON object returned by the the API route (referred to as data below). Any callbacks provided to the fail() method of the returned Deferred object will be passed an instance of AjaxRejection, see Deferred objects.

Arguments:
  • route (string) – Experiment route, e.g. /info/$nodeId

  • data (object) – Optional data to include in request

Returns:

jQuery.Deferred – See Deferred objects

Example

var response = dallinger.get('/node/' + nodeId + '/infos');
// Wait for response and handle data
response.done(function (data) {...});
static dallinger.post(route, data)

Convenience method for making an AJAX POST request to a specified route. Any callbacks provided to the done() method of the returned Deferred object will be passed the JSON object returned by the the API route (referred to as data below). Any callbacks provided to the fail() method of the returned Deferred object will be passed an instance of AjaxRejection, see Deferred objects.

Arguments:
  • route (string) – Experiment route, e.g. /info/$nodeId

  • data (object) – Optional data to include in request

Returns:

jQuery.Deferred – See Deferred objects

Example

var response = dallinger.post('/info/1', {details: {a: 1}});
// Wait for response and handle data or failure
response.done(function (data) {...}).fail(function (rejection) {...});

The dallinger object also provides functions that make requests to specific experiment routes:

static dallinger.createAgent()

Creates a new experiment Node for the current partcipant.

Returns:

jQuery.Deferred – See Deferred objects

Example

var response = dallinger.createAgent();
// Wait for response
response.done(function (data) {... handle data.node ...});
static dallinger.createInfo(nodeId, data)

Creates a new Info object in the experiment database.

Arguments:
  • nodeId (number) – The id of the participant’s experiment node

  • data (Object) – Experimental data (see Info)

Returns:

jQuery.Deferred – See Deferred objects

Example

var response = dallinger.createInfo(1, {details: {a: 1}});
// Wait for response
response.done(function (data) {... handle data.info ...});
static dallinger.getInfo(nodeId, infoId)

Get a specific Info object from the experiment database.

Arguments:
  • nodeId (number) – The id of an experiment node

  • infoId (number) – The id of the Info object to be retrieved

Returns:

jQuery.Deferred – See Deferred objects

Example

var response = dallinger.getInfo(1, 1);
// Wait for response
response.done(function (data) {... handle data.info ...});
static dallinger.getInfos(nodeId)

Get all Info objects for the specified node.

Arguments:
  • nodeId (number) – The id of an experiment node.

Returns:

jQuery.Deferred – See Deferred objects

Example

var response = dallinger.getInfos(1, 1);
// Wait for response
response.done(function (data) {... handle data.infos ...});
static dallinger.getReceivedInfos(nodeId)

Get all the Info objects a node has been sent and has received.

Arguments:
  • nodeId (number) – The id of an experiment node.

Returns:

jQuery.Deferred – See Deferred objects

Example

var response = dallinger.getReceivedInfostInfos(1);
// Wait for response
response.done(function (data) {... handle data.infos ...});
static dallinger.getTransmissions(nodeId, data)

Get all Transmission objects connected to a node.

Arguments:
  • nodeId (number) – The id of an experiment node.

  • data (Object) – Additional parameters, specifically direction (to/from/all) and status (all/pending/received).

Returns:

jQuery.Deferred – See Deferred objects

Example

var response = dallinger.getTransmissions(1, {direction: "to", status: "all"});
// Wait for response
response.done(function (data) {... handle data.transmissions ...});

Additionally, there is a helper method to handle error responses from experiment API calls (see Deferred objects below):

static dallinger.error(rejection)

Handles experiment errors by requesting feedback from the participant and attempts to complete the experiment (and compensate participants).

Arguments:
  • rejection (dallinger.AjaxRejection) – information about the AJAX error.

Example

// Let dallinger handle the error
dallinger.createAgent().fail(dallinger.error);

// Custom handling, then request feedback and complete if possible
dallinger.getInfo(info).fail(function (rejection) {
 ... handle rejection data ...
 dallinger.error(rejection);
});

Deferred objects

All of the above functions make use of jQuery.Deferred, and return Deferred objects. These Deferred objects provide the following methods to facilitate handling asynchronous responses once they’ve completed:

  • .done(callback): Provide a callback to handle data from a successful response

  • .fail(fail_callback): Provide a callback to handle error responses

  • .then(callback[, fail_callback, progress_callback]): Provide callbacks to handle successes, failures, and progress updates.

The fail_callback function will be passed a dallinger.AjaxRejection object which includes detailed information about the error. Unexpected errors should be handled by calling the dallinger.error() method with the AjaxRejection object.

class dallinger.AjaxRejection(options)

Information about a rejected dallinger.get / dallinger.post call.

Properties:

route - Requested experiment route

method - HTTP method used for the request

data - Data that was sent with the request

error - Underlying transport error object

status - HTTP status code from the failed request

response - Parsed JSON object body from the server, {} when the

body is missing, unparseable, or not a JSON object

html - Rendered error HTML from the server response, if present

errorCode - Optional machine-readable error_code from the server

JSON body (for example participant_not_found or assignment_id_missing)

requestJSON - Serialized request details for error reporting

Arguments:
  • options (Object) – Rejection details from the AJAX helper

Experiment Initialization and Completion

In addition to the request functions above, there are a few functions that are used by the default experiment templates to setup and complete an experiment. If you are writing a highly customized experiment, you may need to use these explicitly:

static dallinger.createParticipant()

Create a new experiment Participant by making a POST request to the experiment /participant/ route. If the experiment requires a quorum, the response will not resolve until the quorum is met. If the participant is requested after the quorum has already been reached, the dallinger.skip_experiment flag will be set and the experiment will be skipped.

This method is called automatically by the default waiting room page.

Returns:

jQuery.Deferred – See Deferred objects

Example

// Create a new participant using entry information from dallinger.identity
result = dallinger.createParticipant();
result.done(function () {... handle ``data.status`` ...});
static dallinger.loadParticipant(assignment_info)

Load an existing Participant into the dlgr.identity by making a POST request to the experiment’s /load-participant route with some assignment_info, which can be a scalar assignment_id or an object with entry_information parameters.

dallinger.identity.uniqueId is set only when assignment_info is an object holding the participant’s worker id under the recruiter’s parameter name, such as workerId for MTurk or PROLIFIC_PID for Prolific. Otherwise a stored uniqueId is kept if it ends with the loaded assignment_id, and cleared if it doesn’t.

Returns:

jQuery.Deferred – See Deferred objects

static dallinger.hasAdBlocker(callback)

Determine if the user has an ad blocker installed. If an ad blocker is detected the callback will be executed asynchronously after a small delay.

This method is called automatically from the experiment default template.

Arguments:
  • callback (function) – a function, with no arguments, to call if an ad blocker is running.

static dallinger.submitAssignment()

Notify the experiment that the participant’s assignment is complete. Performs a POST request to the experiment’s /worker_complete route, then redirects the main/parent window to the /recruiter-exit route and closes the secondary window in which the experiment ran.

Returns:

jQuery.Deferred – See Deferred objects

Example

// Mark the assignment complete and perform a custom function when successful
result = dallinger.submitAssignment();
result.done(function (data) {... handle ``data.status`` ...}).fail(
    dallinger.error
);
static dallinger.recruiterExitRoute()

The URL of the participant’s /recruiter-exit page. It carries the participant’s unique_id as well as their participant_id, so an experiment can check that the visitor is that participant.

Returns:

string – The exit page’s path and query string.

static dallinger.submitQuestionnaire(name="questionnaire")

Submits a Question object to the experiment server. This method is called automatically from the default questionnaire page.

Arguments:
  • name (string) – optional questionnaire name

static dallinger.waitForQuorum()

Waits for a WebSocket message indicating that quorum has been reached.

This method is called automatically within createParticipant() and the default waiting room page.

The connection names no participant, since it only listens to the quorum channel, so the experiment’s accept_websocket_connection method is not asked about it.

Returns:

jQuery.Deferred – See Deferred objects

WebSocket connections

These functions open a WebSocket connection to one of the experiment server’s WebSocket routes, as described in Using WebSockets in Dallinger Experiments:

static dallinger.openChatSocket(options)

Open a WebSocket connection to the /chat route, which publishes each message it is sent to the channel the message names.

The connection identifies the participant from dallinger.identity, if there is one. The server then refuses it if that participant does not exist or the experiment’s accept_websocket_connection method says no.

Arguments:
  • options (Object)

  • options.channel (string) – Channel to subscribe to, whose messages are passed to onBroadcast callbacks

  • options.scope (string) – Scope of the connection; null sends none

  • options.session (number) – To play a real-time game, the id of the session, which dallinger.waitForRealtimeSession gives the page. dallinger.joinRealtimeSession sets this and gameChannel itself. The participant must be one of its players, or the server refuses the connection. The socket’s scope should name this load of the page, as the default does, and can’t be null, since the game’s views would then reach every page the player has open.

  • options.gameChannel (string) – Required with session: the game type’s channel, on which send sends the player’s messages to the game. dallinger.joinRealtimeSession sets it itself.

  • options.predict (function) – With session, to show the player’s own moves at once: predict(view, message) returns the view as it would be once the game applied the message. See predictedView.

  • options.interpolate (function) – With session, to show other players moving smoothly: interpolate(a, b, fraction) returns the view fraction of the way from tick view a to tick view b. See interpolatedView.

  • options.interpolationDelay (number) – With interpolate, how many tick intervals behind the session time interpolatedView draws the game

Returns:

dallinger.Socket – The new connection

Example

var chatroom = dallinger.openChatSocket({channel: 'chatroom'});
chatroom.onBroadcast(function (data) {
  if (data.type === 'message') { ... }
});
chatroom.send('chatroom', {type: 'message', content: 'Hello'});
static dallinger.openExperimentSocket(options)

Open a WebSocket connection to the /experiment-socket route, which passes each message it is sent to the experiment’s handle_websocket_message method on the web process holding the connection.

The connection identifies the participant from dallinger.identity, and the server refuses it if that participant does not exist or the experiment’s accept_websocket_connection method says no.

Arguments:
  • options (Object) – The same options as dallinger.openChatSocket

Returns:

dallinger.Socket – The new connection

Example

var socket = dallinger.openExperimentSocket();
socket.onDirect(function (data) {
  if (data.type === 'move_accepted') { ... }
});
socket.send('moves', {type: 'move', action: 'rock'});
class dallinger.Socket(route, options)

A connection to one of the experiment server’s WebSocket routes, created with dallinger.openChatSocket or dallinger.openExperimentSocket.

The connection is a ReconnectingWebSocket, available as the raw property, which reconnects with a growing delay whenever it is dropped. A connection the server refuses is not retried.

A socket opened with a session is a player’s page in a real-time game. Each time it connects, it joins the session and is sent the game as it stands, so a player whose connection drops carries on from where the game has got to. Send the player’s moves with send, draw the game in onView, and move on once resultSaved says the game is over and saved. The socket also keeps track of the server’s clock, so the page can tell the time as the game sees it (see sessionTime). A fast game can show the player’s own moves at once with predictedView, and other players moving smoothly with interpolatedView.

Sessions need dallinger-realtime.js, which the base layout loads when the experiment’s realtime_games property lists any game types. A page that replaces the layout’s libs block, or doesn’t use the layout, loads it itself, after dallinger2.js.

Arguments:
  • route (string) – Path of the WebSocket route

  • options (Object) – See dallinger.openChatSocket

Example

dallinger.joinRealtimeSession('sealed_bid').done(function (socket) {
  socket.onView(function (view) {
    $('#bids-made').text(view.bids_made);
  });
  $('#bid').on('click', function () {
    socket.send('sealed_bid', {bid: Number($('#amount').val())});
  });
  socket.resultSaved().done(function () {
    dallinger.goToPage('questionnaire');
  });
});
dallinger.Socket.send(channel, payload)

Send a message to channel. The /chat route publishes it to that channel’s subscribers, and the /experiment-socket route passes it to the experiment’s handle_websocket_message method, with channel as the channel_name.

On a socket that joined a session, send the player’s moves on the gameChannel. They go only to the game type’s apply method, which gets a string that holds JSON parsed. send returns the message’s number, which onRejected passes back if the game rejects the move. Messages over the game type’s max_messages_per_second limit are dropped.

A message sent while the connection is down waits, and goes out in order once the connection reopens. Once the socket is closed or refused, waiting messages are dropped and send sends nothing.

Arguments:
  • channel (string) – The channel to send on

  • payload (Object|string) – The message. Anything but a string is sent as JSON.

Returns:

number|undefined – The message’s number, for a message sent on a session’s gameChannel. Nothing for any other message, or once the socket is closed or refused.

dallinger.Socket.onBroadcast(callback)

Call callback with each message published to this socket’s channel, whether it was sent by the experiment or by another client.

The callback is passed the payload parsed as JSON, or the payload string itself if it is not JSON, followed by the payload string.

Arguments:
  • callback (function) – Called with each message

Returns:

dallinger.Socket – This socket

dallinger.Socket.onDirect(callback)

Call callback with each message sent to this participant with the experiment’s publish_to_participants method. The callback is passed the same arguments as an onBroadcast callback.

Arguments:
  • callback (function) – Called with each message

Returns:

dallinger.Socket – This socket

dallinger.Socket.onOpen(callback)

Call callback each time the connection opens, including after a reconnect. Messages published while the connection was down are not replayed, so this is where a page should fetch anything it may have missed. Messages held by send have already been sent when the callback runs.

The callback is passed the open event, whose isReconnect property is false the first time the connection opens.

Arguments:
  • callback (function) – Called with the open event

Returns:

dallinger.Socket – This socket

dallinger.Socket.onRefused(callback)

Call callback with the close code and reason if the server refuses the connection, as /experiment-socket and /chat do for an unknown participant or when accept_websocket_connection returns false. The connection is not retried either way, and without a callback the refusal is logged to the console.

Arguments:
  • callback (function) – Called with the close code and reason

Returns:

dallinger.Socket – This socket

dallinger.Socket.close()

Close the connection for good, discarding any messages held by send.

The returned Deferred resolves once the connection has closed, so that a page can let messages it has already sent reach the server before it navigates away.

Returns:

jQuery.Deferred – See Deferred objects

Example

socket.send('chatroom', {type: 'log', content: 'Goodbye.'});
socket.close().always(function () {
  dallinger.goToPage('questionnaire');
});
dallinger.pageScope

A value identifying this page load. Sockets opened with dallinger.openChatSocket or dallinger.openExperimentSocket send it as their scope unless they are given another, so an experiment which replies with the scope its handler was given reaches the page that sent the message, and not an earlier page whose socket is still open.

dallinger.DIRECT_CHANNEL

The channel on which directed messages, sent with the experiment’s publish_to_participants method, arrive. It is reserved for Dallinger’s own use, so a client may neither subscribe nor send to it.

Real-Time Sessions

A socket opened with a session joins a session of one of the experiment’s real-time games, and has the methods below. A page usually joins its session with dallinger.joinRealtimeSession, which waits for the session and resolves with the socket. The two functions below, the methods and dallinger.browserTime are defined in dallinger-realtime.js. The base layout loads that script after dallinger2.js when the experiment’s realtime_games property lists any game types. A page that replaces the layout’s libs block, or doesn’t use the layout, loads it itself.

static dallinger.joinRealtimeSession(gameChannel, options)

Wait for the experiment to start a session of a game type with this participant as a player, then join it, and get the socket to play it on. This is how a game’s page usually starts, since the page often opens before its session exists: the experiment starts the session once a group is complete.

It waits as waitForRealtimeSession does, on a connection of its own, so the promise resolves at once if the participant is already playing a session of the game type, and a page that is reloaded during a game finds its session again. A session whose ending has been saved isn’t reported. It then opens the socket with openExperimentSocket. Set the socket’s callbacks, such as onView, in the done callback, which runs before the socket has received anything.

The options are afterSession, as for waitForRealtimeSession, and the options of openExperimentSocket other than session and gameChannel, which it sets itself: predict, interpolate, interpolationDelay, channel and scope. Both connections use the scope, so the experiment’s accept_websocket_connection sees the same one on each. An experiment that names its pages itself can pass its name for the page as the scope, but each load of a page needs a scope of its own: if a reloaded page reuses its scope while the earlier load is still connected, the session can briefly mix up the two loads’ messages. A name that stays the same when the page is reloaded can have dallinger.pageScope added to it. The scope can’t be null, since the game’s views would then reach every page the player has open. A page that also uses a chat channel waits with waitForRealtimeSession and opens its socket with openChatSocket.

The promise is rejected, with the close code and reason, if the server refuses the connection that waits for the session, and with the error if the socket can’t be opened. A refusal of the socket itself reaches the socket’s onRefused callback. Call the promise’s cancel method to stop waiting, which leaves the promise unresolved. Once the promise has resolved, cancel does nothing, and the socket’s close method closes the socket.

Arguments:
  • gameChannel (string) – The game type’s channel

  • options (Object)

  • options.afterSession (number) – The id of a session the page already has, so that only a newer one counts

  • options.scope (string) – The page’s scope, on both connections

Returns:

jQuery.Promise – Resolves with the session’s dallinger.Socket. See Deferred objects

Example

dallinger.joinRealtimeSession('sealed_bid').done(function (socket) {
  socket.onView(function (view) {
    $('#bids-made').text(view.bids_made);
  });
  $('#bid-form').on('submit', function (event) {
    event.preventDefault();
    socket.send('sealed_bid', {bid: Number($('#bid').val())});
  });
});
static dallinger.waitForRealtimeSession(gameChannel, options)

Wait for the experiment to start a session of a game type with this participant as a player, and get the session’s id. Most pages use joinRealtimeSession, which also opens the socket. This is for a page that needs the id before it joins, or that joins on /chat with openChatSocket.

If the participant is already a player in a running session of the game type, the promise resolves at once, with the newest such session, so a page that is reloaded during a game finds its session again. A session whose ending has been saved isn’t reported.

When the participant plays several sessions of the game type, one after another, pass the id of the session the page already has as afterSession, so that only a newer one counts. Otherwise a still-running earlier session is the answer.

It waits on a connection of its own to the /experiment-socket route, which closes once it has the id. Like any experiment socket, that connection has the scope option’s scope, is checked by the experiment’s accept_websocket_connection method, and its connecting and disconnecting are published on the dallinger_control channel. The promise is rejected, with the close code and reason, if the server refuses the connection, for example when gameChannel isn’t one of the experiment’s game types’ channels.

Call the promise’s cancel method to stop waiting. It closes the connection and leaves the promise unresolved.

Arguments:
  • gameChannel (string) – The game type’s channel

  • options (Object)

  • options.afterSession (number) – The id of a session the page already has, so that only a newer one counts

  • options.scope (string) – Scope of the connection that waits; null sends none

Returns:

jQuery.Promise – Resolves with the session’s id. See Deferred objects

Example

dallinger.waitForRealtimeSession('sealed_bid').done(function (sessionId) {
  var socket = dallinger.openChatSocket({
    channel: 'chatroom',
    session: sessionId,
    gameChannel: 'sealed_bid'
  });
  socket.onView(function (view) {
    $('#bids-made').text(view.bids_made);
  });
});
dallinger.Socket.onView(callback)

Call callback with each new view of the game: what the game type’s view method lets this player see. Draw the game from it. The page gets a view when it joins the session, again after a reconnect, and whenever the game changes, until the session ends. The callback only gets views newer than the last one, so it can always draw what it’s given.

The callback is passed the view, then an object with details about it:

  • view: the view itself

  • number: a later view has a higher number

  • time: the session time the view shows, in seconds (see sessionTime)

  • kind: "tick" if the game type’s tick method made the change, otherwise "message"

  • last_processed: the number of this page’s latest message that the game has applied or rejected (see send), or null

  • rejected: this page’s messages the game rejected since its last view, also passed to onRejected

  • ended: why the session ended, once it has, otherwise null

  • clock: the server’s clock, in seconds since 1970, when the session time was time

  • tick_rate: the game type’s tick_rate, how many tick views arrive a second

Arguments:
  • callback (function) – Called with each new view and its details

Returns:

dallinger.Socket – This socket

dallinger.Socket.onRejected(callback)

Call callback each time the game rejects one of this page’s messages, with the number send returned for the message and the reason the game type’s apply method gave Reject. Use it to tell the player why a move didn’t count.

Each rejection is reported once. A message rejected just before the connection dropped isn’t reported. A page with two sockets in the same session hears each rejection on both.

Arguments:
  • callback (function) – Called with the message’s number and the reason

Returns:

dallinger.Socket – This socket

Example

socket.onRejected(function (number, reason) {
  $('#error').text('That bid didn\'t count: ' + reason);
});
dallinger.Socket.onEnded(callback)

Call callback once, as soon as the page learns the session has ended, with the reason it ended and this player’s final view. Use it to stop taking moves and show how the game turned out. Don’t submit the page yet, since the result may not be saved (see resultSaved).

The reason is the one the game type’s outcome method was passed:

  • "finished": the game type’s is_over method returned true

  • "max_duration": the session ran for the game type’s max_duration

  • "not_joined": no player other than a bot joined within the game type’s join_timeout

  • "failed": the game’s code failed

  • or the reason the experiment passed to end_realtime_session

It also runs for a page that joins after the session has ended, which gets no views. The final view can reach onView after this callback, so show the result from the view passed here.

Arguments:
  • callback (function) – Called with the reason and the final view

Returns:

dallinger.Socket – This socket

dallinger.Socket.onResultSaved(callback)

Call callback once, when the session’s result has been saved, so the page can move on. It does what resultSaved does, as a callback, and is passed the same object.

Arguments:
  • callback (function) – Called with the saved result

Returns:

dallinger.Socket – This socket

dallinger.Socket.resultSaved()

Wait for the session’s result to be saved. Wait for this before the page is submitted or moves on, so that the experiment can read the result, for example to pay a bonus.

The returned promise resolves with an object holding:

  • status: "ended", or "failed" if the game’s code failed

  • reason: why the session ended (see onEnded)

  • view: this player’s final view

A failed session’s result is saved too, so the page can move on either way. The result is usually saved a moment after the session ends. A page that shouldn’t wait indefinitely can use onEnded to learn that the game is over before then.

The promise is rejected if the socket is closed first, or if the server refuses the connection, for example to a page that joins long after the session ended. A refusal passes the close code and reason.

Returns:

jQuery.Promise – See Deferred objects

Example

socket.resultSaved().done(function (result) {
  dallinger.goToPage('questionnaire');
});
dallinger.Socket.onClock(callback)

Call callback each time the socket measures the server’s clock. Most pages don’t need this, since serverTime and sessionTime already use the measurements. It is for a page that wants to show or log how closely its clock matches the server’s.

The socket measures the clock when it connects, then about every 30 seconds until the session ends. Each measurement is saved with the session’s records, so an analysis can put the browser times of players’ messages on the server’s clock. Each one counts as a message toward the game type’s max_messages_per_second limit.

The callback is passed an object holding:

  • browser_time: a moment on the browser’s clock (see dallinger.browserTime), in seconds since 1970

  • server_time: the server’s clock at that same moment, in seconds since 1970

  • round_trip: how long the server took to answer, in seconds. server_time can be off by up to half of this.

Arguments:
  • callback (function) – Called with each measurement

Returns:

dallinger.Socket – This socket

dallinger.Socket.serverTime(browserTime)

Convert a time on the browser’s clock to the server’s clock. The two clocks can be seconds apart or more, so convert times before comparing what happened on different players’ pages.

Arguments:
  • browserTime (number) – A time from dallinger.browserTime, in seconds since 1970. Leave it out to convert the time now.

Returns:

number|null – The same moment on the server’s clock, in seconds since 1970, or null until the socket’s first measurement, which arrives shortly after it connects

Example

var serverNow = socket.serverTime();
var clickedOnServer = socket.serverTime(clickedAt);
dallinger.Socket.sessionTime()

The session’s time now, in seconds: the now the game type’s methods would be passed at this moment. Use it to count down to a deadline the game puts in its view, or to show how long ago something in the view happened.

It keeps counting between views. A session’s clock stops while the session is paused, for example during a redeploy, so the next view can move the time back a little. Once the session has ended, the time stays at the final view’s time.

Returns:

number|null – The session time in seconds, or null for a moment after the socket connects, until it has a view and has measured the server’s clock

Example

var deadline = null;
socket.onView(function (view) { deadline = view.deadline; });
setInterval(function () {
  var now = socket.sessionTime();
  if (now !== null && deadline !== null) {
    $('#timer').text(Math.ceil(Math.max(0, deadline - now)));
  }
}, 250);
dallinger.Socket.predictedView()

The view to draw the player’s own piece from, with their moves shown at once instead of a round trip later. Call it each time the page draws. Needs the predict option.

It is the newest view, with the player’s moves that the game hasn’t handled yet applied by predict, in the order they were sent. predict(view, message) gets a view and a message as it was passed to send, and returns the view as it would be once the game applied the message. It may change the view it’s given and return nothing, but must not change the message.

predict has to do to the view what the game type’s apply method does to the state, or the player’s piece jumps when the next view arrives. So have each movement message say how far, or for how long, the player moved, rather than having tick move players while a key is held, which the page can’t predict.

A move the game rejects is undone by the next view, which in a game with a tick_rate above 0 is the next tick’s view at the latest. A message dropped for going over the game type’s max_messages_per_second limit stays predicted until the game handles a later message from the page.

Draw from the returned view without changing it. Once the session has ended, it is the final view.

Returns:

Object|null – The predicted view, or null before the first view (unless the session has ended)

Example

var socket = dallinger.openExperimentSocket({
  session: sessionId,
  gameChannel: 'moves',
  predict: function (view, message) {
    view.me.x += message.dx;
    view.me.y += message.dy;
  }
});
document.addEventListener('keydown', function (event) {
  if (event.key === 'ArrowRight') { socket.send('moves', {dx: 1, dy: 0}); }
});
function draw() {
  var view = socket.predictedView();
  if (view !== null) { drawPlayer(view.me); }
  requestAnimationFrame(draw);
}
requestAnimationFrame(draw);
dallinger.Socket.interpolatedView()

The view to draw other players from, so they move smoothly instead of jumping from one tick view to the next. Call it each time the page draws. Needs the interpolate option and a game type whose tick_rate is above 0. A game that also uses prediction draws the player’s own piece from predictedView.

It shows the game interpolationDelay tick intervals (two by default) behind sessionTime. interpolate(a, b, fraction) gets the tick views either side of that time and how far between them it falls, from 0 to 1, and returns a new view in between, leaving a and b unchanged. A longer delay copes better with tick views that arrive late, but shows the game further in the past.

Draw from the returned view without changing it. Once the session has ended, it is the final view.

Returns:

Object|null – The view to draw, or null before the first tick view (unless the session has ended)

Example

var socket = dallinger.openExperimentSocket({
  session: sessionId,
  gameChannel: 'moves',
  interpolate: function (a, b, fraction) {
    return {
      others: a.others.map(function (player, i) {
        var next = b.others[i];
        return {
          x: player.x + (next.x - player.x) * fraction,
          y: player.y + (next.y - player.y) * fraction
        };
      })
    };
  }
});
function draw() {
  var view = socket.interpolatedView();
  if (view !== null) { view.others.forEach(drawPlayer); }
  requestAnimationFrame(draw);
}
requestAnimationFrame(draw);
static dallinger.browserTime()

The time now on the browser’s clock, in seconds since 1970. Use it to note when something happened on the page, and pass that time to a session socket’s serverTime to put it on the server’s clock.

This clock keeps counting steadily even if someone changes the computer’s clock while the page is open. The browser times saved with a session’s messages come from it too.

A browser event’s timeStamp comes from the same clock, counted in milliseconds from performance.timeOrigin, so an event’s browser time is (performance.timeOrigin + event.timeStamp) / 1000. That is closer to the moment a key was pressed or the mouse clicked than calling browserTime in the event handler.

Returns:

number – Seconds since 1970

Example

document.addEventListener('keydown', function (event) {
  var pressedAt = (performance.timeOrigin + event.timeStamp) / 1000;
  var pressedAtOnServer = socket.serverTime(pressedAt);
});

Helper functions and properties

Finally, there are a few miscellaneous utility functions and properties which are useful when writing a custom experiment:

static dallinger.getUrlParameter(sParam)

Returns a url query string value given the parameter name.

Arguments:
  • sParam (string) – name of url parameter

Returns:

string|boolean – the parameter value if available; true if parameter is in the url but has no value;

Example

// Given a url with ``?param1=aaa&param2``, the following returns "aaa"
dallinger.getUrlParameter("param1");
// this returns true
dallinger.getUrlParameter("param2");
// and this returns null
dallinger.getUrlParameter("param3");
static dallinger.goToPage(page)

Advance the participant to a given html page; the participant_id will be included in the url query string.

Arguments:
  • page (string) – Name of page to load, the .html extension should not be included.

static dallinger.stopReconnectingIfRefused(socket, callback)

Stop a ReconnectingWebSocket retrying a connection the server refused.

ReconnectingWebSocket reconnects after every close and reports the close code on its connecting event rather than on close, so a refusal is otherwise indistinguishable from a dropped network connection and repeats forever.

The socket is left in the CLOSED state, so code that polls readyState can tell a refusal from a reconnect in progress.

Arguments:
  • socket (ReconnectingWebSocket) – the socket to watch

  • callback (function) – called with the close code and reason when the connection is refused

Returns:

ReconnectingWebSocket – the socket that was passed in

dallinger.identity

dallinger.identity provides information about the participant. It has the following string properties:

recruiter - Type of recruiter

hitId - MTurk HIT Id

workerId - MTurk Worker Id

assignmentId - MTurk Assignment Id

uniqueId - MTurk Worker Id and Assignment Id

mode - Dallinger experiment mode

participantId - Dallinger participant Id

dallinger.WEBSOCKET_REFUSED

The close code Dallinger sends when it refuses a connection outright, for example, when the participant_id is invalid. The browser’s ReconnectingWebSocket should not retry on this code.