Skip to main content

What is a Timeline?

In Cajal (and jsPsych), a timeline is the sequence of events that make up your experiment. Think of it as the blueprint that defines what participants see, when they see it, and in what order.
The timeline controls the flow of your experiment from start to finish. It specifies not just individual trials, but also how trials repeat, randomize, and connect together.

Timeline vs. Frames

  • Frame: A single screen or moment in time (e.g., a fixation cross, a stimulus display)
  • Timeline: The complete sequence of frames that make up your task
Example: A Stroop trial timeline might be:
Frame 1: Fixation (500ms) → Frame 2: Stimulus + Response → Frame 3: Feedback (1000ms) → Frame 4: Blank (500ms)
This 4-frame sequence would then loop for 50 trials with different stimuli.

Frame-Based Timeline Structure

Understanding Frames

Frames are the building blocks of your timeline. Each frame represents a discrete moment in the experiment.

Single Frame

One screen with components (e.g., “Show fixation cross”)

Frame Sequence

Multiple frames in order (e.g., “Fixation → Stimulus → Feedback”)

Frame Duration

How long each frame displays (fixed time or until response)

Frame Transitions

Auto-advance or wait for response

Frame Duration Options

Each frame can display for:
  1. Fixed Duration: Exact time in milliseconds (e.g., 500ms)
  2. Until Response: Wait for participant input (0ms = unlimited)
  3. Maximum Duration: Display up to X ms, but advance on response
  4. Conditional Duration: Based on previous response or trial variable
Fixation cross for exactly 500ms
Frame 1:
- Component: Black Fixation Cross
- Duration: 500ms
- Auto-advance: Yes
This frame will display for exactly 500ms, then automatically move to the next frame.

Timeline Variables

Timeline variables are the secret to running multiple trials with different stimuli while using the same trial structure.

What Are Timeline Variables?

Timeline variables define per-trial data that changes across repetitions. Instead of creating 50 separate trials, you create one trial template and one table of variables.
Think of timeline variables as a spreadsheet where each row is one trial, and each column is a variable that changes per trial (stimulus word, correct answer, condition, etc.).

Example: Stroop Task Timeline Variables

| word    | color  | congruent | correct_key |
|---------|--------|-----------|-------------|
| RED     | red    | true      | r           |
| RED     | blue   | false     | b           |
| BLUE    | blue   | true      | b           |
| BLUE    | red    | false     | r           |
| GREEN   | green  | true      | g           |
| GREEN   | red    | false     | r           |
| YELLOW  | yellow | true      | y           |
| YELLOW  | blue   | false     | b           |

How Timeline Variables Work

  1. Define the table: Create columns for each variable that changes per trial
  2. Reference variables: Use {{variable_name}} in component properties
  3. Set repetition: Specify how many rows to use (all, subset, or specific count)
  4. Randomize: Optionally randomize row order
1

Create Variable Columns

Define what changes per trial (stimulus, condition, correct answer, etc.)
2

Fill in Rows

Each row represents one trial with specific values for each variable
3

Link to Components

Use {{variable_name}} syntax in component properties to reference variables
4

Configure Looping

Set how many trials run (all rows, subset, or repeat rows)

Trial Sequences and Loops

Basic Looping

The simplest timeline loops through all rows of your timeline variables exactly once. Example: 8 rows in timeline variables = 8 trials

Basic Loop Configuration

Settings:
  • Repetitions: 1 (each row once)
  • Randomize: Yes
  • Sampling: Without replacement (each row used once)
Result: 8 randomized trials, each with different stimulus values

Advanced Looping Options

Use case: Repeat each condition multiple timesConfiguration:
  • Timeline Variables: 8 rows
  • Repetitions: 3
  • Result: 24 trials (each row appears 3 times)
Best for: Increasing trial count while maintaining balanced conditions
Use case: Randomly sample subset of trialsConfiguration:
  • Timeline Variables: 100 rows
  • Sample Size: 20 trials
  • Sampling: Random without replacement
  • Result: 20 trials randomly selected from 100 options
Best for: Large stimulus sets where you want variety without running all trials
Use case: Allow same trial to appear multiple timesConfiguration:
  • Timeline Variables: 10 rows
  • Sample Size: 30 trials
  • Sampling: Random with replacement
  • Result: 30 trials, some rows may repeat
Best for: When you want more trials than unique stimuli
Use case: Group trials into distinct blocksConfiguration:
  • Block 1: Congruent trials only (filter congruent == true)
  • Block 2: Incongruent trials only (filter congruent == false)
  • Order: Randomize within blocks, counterbalance block order
Best for: Comparing performance across conditions

Randomization and Counterbalancing

Randomization Options

Cajal supports multiple randomization strategies:
Strategy: Completely random trial orderConfiguration:
  • Randomize: Yes
  • Constraints: None
Example: Stroop task with 48 trials in completely random orderBest for: Most cognitive tasks where order effects are minimal

Counterbalancing

Counterbalancing ensures condition order varies systematically across participants.
Method: Alternate condition order based on participant IDExample:
  • Participant 1, 3, 5…: Condition A → Condition B
  • Participant 2, 4, 6…: Condition B → Condition A
Implementation: Use conditional timeline branching based on participant ID (odd/even)
Method: Systematically rotate condition order across participantsExample (3 conditions):
  • Participant 1: A → B → C
  • Participant 2: B → C → A
  • Participant 3: C → A → B
Implementation: Generate different timeline variable orders based on participant number
Method: Alternate which key maps to which responseExample:
  • Group 1: Z = Left, M = Right
  • Group 2: M = Left, Z = Right
Implementation: Use timeline variables to swap correct answer mappings

Sequential vs. Conditional vs. Randomized Flow

Sequential Flow

The simplest timeline: frames advance in a fixed order. Use case: Standard trial structure where every trial follows the same sequence

Conditional Flow

Timeline branches based on participant responses or trial variables. Use case: Adaptive tasks, branching experiments, conditional feedback
Logic: Show different feedback based on correctness
Frame 3: Conditional Feedback
- If response == correct_answer:
    Show "Correct!" (green, 500ms)
- Else:
    Show "Incorrect" (red, 1000ms)

Randomized Flow

Trial order determined randomly at runtime. Use case: Prevent order effects, increase generalizability

Randomization Levels

Within-Trial: Randomize component positions (e.g., left/right stimulus placement)Between-Trial: Randomize trial order from timeline variablesBetween-Block: Randomize block order (counterbalanced across participants)

Timeline Best Practices

Use Timeline Variables for Repetition

Don’t: Create 50 separate trial frames manuallyDo: Create 1 trial template + 50-row timeline variable tableThis reduces errors and makes updates easier.

Balance Your Conditions

Ensure equal trials per condition in your timeline variables.Example: 24 congruent trials, 24 incongruent trials (not 30 vs 18)

Include Practice Trials

Add a separate practice timeline before main trials:
  • Fewer trials (4-8 typically)
  • Same structure as main trials
  • Show feedback (even if hidden in main trials)
  • Allow participants to repeat if needed

Use Appropriate ISIs

Inter-stimulus interval (ISI) prevents visual persistence and resets attention.Typical ISIs:
  • 500ms: Standard cognitive tasks
  • 1000ms: After complex stimuli or feedback
  • 2000ms: Between blocks or conditions
  • Variable (500-1500ms): Prevent anticipatory responses

Test Timing Accuracy

Browser-based timing is accurate to ~10-20ms, sufficient for most psychology tasks.Tips for timing precision:
  • Preload all images before trials start
  • Use simple stimuli for timing-critical tasks
  • Test on target hardware (desktop vs mobile)
  • Avoid video backgrounds or animations during critical timing

Consider Mobile Compatibility

If participants may use mobile devices:
  • Use button responses instead of keyboard
  • Increase touch target sizes (min 44x44px)
  • Test on smaller screens
  • Avoid complex layouts that may not fit

Common Timeline Patterns

Pattern 1: Simple Repeated Trials

Use case: Basic cognitive task with identical trial structure
Frame 1: Fixation (500ms)
Frame 2: Stimulus + Response (until response)
Frame 3: Blank ISI (500ms)

Pattern 2: Practice → Test Blocks

Use case: Training phase before main experiment
Timeline Variables: 4 rows
Repetitions: 1
Randomize: Yes
Feedback: Shown
Instructions: "This is practice. You will see feedback."

Pattern 3: Study → Delay → Test

Use case: Memory experiments with encoding and retrieval phases
Timeline Variables: 30 words
Display: 2 seconds per word
Response: None (just viewing)
Randomize: Yes

Pattern 4: Adaptive Difficulty

Use case: Adjust task difficulty based on performance
Trial N:
- Stimulus: Difficulty level based on previous accuracy
- Response: Collect answer
- Calculate: Running accuracy

After Trial:
- If last 10 trials > 80% correct → Increase difficulty
- If last 10 trials < 60% correct → Decrease difficulty
- Else → Maintain current difficulty

Next Trial:
- Use updated difficulty level

Timeline Variables Reference

Common Variable Types

Variable TypeExamplePurpose
Stimulus Contentword, image_url, numberWhat to display
Correct Answercorrect_key, correct_buttonScoring responses
Condition Tagscongruent, condition, blockExperimental design
Timingstimulus_duration, isi_durationVariable timing
Positionstimulus_x, stimulus_ySpatial control
Metadatatrial_type, difficulty_levelData analysis

Variable Naming Best Practices

✅ word (clear, concise)
✅ correct_answer (descriptive)
✅ image_url (indicates type)
✅ congruent (boolean condition)
✅ stimulus_duration_ms (includes units)

Advanced Timeline Features

Nested Timelines

Create timelines within timelines for complex experimental structures. Example: A multi-block experiment
Experiment Timeline:
├── Consent Form
├── Instructions
├── Practice Block (nested timeline)
│   ├── Practice Instructions
│   ├── Practice Trials (10 trials)
│   └── Practice Feedback Summary
├── Break (1 minute)
├── Main Block 1 (nested timeline)
│   ├── Block 1 Instructions
│   └── Block 1 Trials (50 trials)
├── Break (1 minute)
├── Main Block 2 (nested timeline)
│   ├── Block 2 Instructions
│   └── Block 2 Trials (50 trials)
└── Debriefing

Timeline Functions

Use JavaScript functions to dynamically generate timeline properties.
// Select stimulus based on previous accuracy
stimulus: function() {
  const lastAccuracy = getAccuracy();
  return lastAccuracy > 0.8 ? 'hard_stimulus.png' : 'easy_stimulus.png';
}

Timeline Looping with Conditions

Loop through trials until a condition is met (instead of fixed count). Example: Continue trials until participant reaches 80% accuracy
Loop Configuration:
- Loop Type: While condition true
- Condition: accuracy < 0.80
- Max Iterations: 100 (safety limit)
- Min Iterations: 20 (ensure minimum data)

Data Collection from Timelines

Automatic Timeline Data

Every trial automatically records:
Data FieldDescription
trial_indexSequential trial number (0-indexed)
time_elapsedMilliseconds since experiment start
trial_typejsPsych plugin used
internal_node_idTimeline position identifier

Custom Timeline Data

Add custom data fields to each trial:
Timeline Variables:
| word  | color | congruent | correct_key |
|-------|-------|-----------|-------------|
| RED   | red   | true      | r           |
| BLUE  | blue  | true      | b           |

Additional Data Saved:
- word: "RED"
- color: "red"
- congruent: true
- correct_key: "r"
- (plus response, rt, correct from response component)

Timeline-Level Data

Add data that applies to all trials in a timeline:
Timeline Settings:
- Block Number: 1
- Condition: "experimental"
- Session ID: "abc123"

Result: Every trial in this timeline gets these additional data fields

Performance Considerations

Optimizing Timeline Performance

Preload Media

Load all images, audio, and video before trials start.Why: Prevents delays during trial presentationHow: Cajal automatically preloads media referenced in timeline variables

Minimize Timeline Variable Rows

Use repetition settings instead of duplicating rows.Don’t: 1000 rows with many duplicatesDo: 50 unique rows × 20 repetitions

Avoid Complex Calculations Per Trial

Pre-compute values in timeline variables when possible.Don’t: Calculate stimulus position on every trialDo: Pre-define positions in timeline variable columns

Test on Target Devices

Performance varies significantly between desktop and mobile.Desktop: Faster, more consistent timingMobile: Slower, more variable (test your actual design)

Troubleshooting Common Timeline Issues

Problem: Trials appear in same order every timeSolution:
  • Check “Randomize” setting is enabled
  • Ensure sampling method is set correctly
  • Verify timeline variables table exists
Problem: {{variable_name}} appears literally instead of valueSolution:
  • Check variable name spelling matches exactly
  • Ensure timeline variables table has this column
  • Verify variable is wrapped in double curly braces: {{name}}
Problem: More or fewer trials than expectedSolution:
  • Check repetition setting (rows × repetitions = total trials)
  • Verify sampling method (with/without replacement)
  • Look for nested timeline repetitions multiplying count
Problem: Stimuli display for wrong durationSolution:
  • Verify duration is in milliseconds (not seconds)
  • Check for response-based advancement overriding duration
  • Ensure preloading is complete before trials start
  • Test on target hardware (timing varies by device)
Problem: Some conditions appear more than othersSolution:
  • Count rows per condition in timeline variables
  • Ensure equal representation in source table
  • Check sampling method isn’t creating imbalance

Examples: Complete Timelines

Example 1: Basic Stroop Task

| word   | color  | congruent | correct_key |
|--------|--------|-----------|-------------|
| RED    | red    | true      | r           |
| RED    | blue   | false     | b           |
| BLUE   | blue   | true      | b           |
| BLUE   | red    | false     | r           |
| GREEN  | green  | true      | g           |
| GREEN  | blue   | false     | b           |
| YELLOW | yellow | true      | y           |
| YELLOW | red    | false     | r           |

Example 2: Recognition Memory Task

| item          | item_type |
|---------------|-----------|
| elephant.jpg  | animal    |
| hammer.jpg    | tool      |
| ...           | ...       |

Next Steps