diff --git a/.changeset/young-pants-run.md b/.changeset/young-pants-run.md new file mode 100644 index 00000000..e63aef22 --- /dev/null +++ b/.changeset/young-pants-run.md @@ -0,0 +1,5 @@ +--- +"@jspsych-contrib/plugin-html-keyboard-response-raf": patch +--- + +Adjusted how display durations are tracked to count frames rather than rely on timers diff --git a/packages/plugin-html-keyboard-response-raf/src/index.ts b/packages/plugin-html-keyboard-response-raf/src/index.ts index badef6bf..29acf3a4 100644 --- a/packages/plugin-html-keyboard-response-raf/src/index.ts +++ b/packages/plugin-html-keyboard-response-raf/src/index.ts @@ -51,6 +51,14 @@ const info = { pretty_name: "Response ends trial", default: true, }, + /** + * FPS for requestAnimationFrame + */ + fps: { + type: ParameterType.INT, + pretty_name: "FPS", + default: 60, + }, }, }; @@ -67,8 +75,8 @@ class HtmlKeyboardResponseRafPlugin implements JsPsychPlugin { static info = info; private keyboardListener; - private hideStimulusTime: number = Infinity; - private endTrialTime: number = Infinity; + private hideStimulusFrameCount: number = Infinity; + private endTrialFrameCount: number = Infinity; private stimulusIsHidden = false; private currAnimationFrameHandler: number; @@ -88,6 +96,8 @@ class HtmlKeyboardResponseRafPlugin implements JsPsychPlugin { key: null, }; + var frame_counter = 0; + // draw this.currAnimationFrameHandler = requestAnimationFrame(() => { const initialDisplayTime = performance.now(); @@ -107,28 +117,29 @@ class HtmlKeyboardResponseRafPlugin implements JsPsychPlugin { // hide stimulus if stimulus_duration is set if (trial.stimulus_duration !== null) { - this.hideStimulusTime = initialDisplayTime + trial.stimulus_duration; + this.hideStimulusFrameCount = Math.round(trial.stimulus_duration / (1000 / trial.fps)); } // end trial if trial_duration is set if (trial.trial_duration !== null) { - this.endTrialTime = initialDisplayTime + trial.trial_duration; + this.endTrialFrameCount = Math.round(trial.trial_duration / (1000 / trial.fps)); } + console.log(performance.now()); this.currAnimationFrameHandler = requestAnimationFrame(checkForEnd); }); const checkForEnd = () => { - const currTime = performance.now(); - if (currTime >= this.hideStimulusTime && !this.stimulusIsHidden) { + frame_counter++; + if (frame_counter >= this.hideStimulusFrameCount && !this.stimulusIsHidden) { this.stimulusIsHidden = true; display_element.querySelector( "#jspsych-html-keyboard-response-stimulus" ).style.visibility = "hidden"; - console.log(currTime - this.hideStimulusTime); + console.log(frame_counter, performance.now()); } - if (currTime >= this.endTrialTime) { - console.log(currTime - this.endTrialTime); + if (frame_counter >= this.endTrialFrameCount) { + console.log(frame_counter, performance.now()); end_trial(); } else { this.currAnimationFrameHandler = requestAnimationFrame(checkForEnd);