Help coding a visible countdown timer

Twine Version: 2.3.5
Story Format: Sugarcube

Greetings good citizens of the community. Coding beginner here.

I’m trying to incorporate a puzzle with a visible countdown timer into my game/story: the player enters a passage and an immediate visible clock ticks down; the player continues to navigate through passages until the time elapses, at which point they are taken to a “failure” passage (unless they’ve succeeded at the puzzle in that time).

I’ve managed to make everything work other than the “visible” bit. I found this bit of code online to use for an invisible timer:

In passage:

<<set $start to Date.now()>>

In Story Javascript:

Config.navigation.override = function (d) { if (State.variables.start) { if ((Date.now() - State.variables.start) > 180000) { return 'Time up!'; } } return false; };

Unfortunately, when I’ve tried to code a visible timer in my StoryCaption passage I find it disappears instantly (as the player navigates to a new passage?). I’m using this code that I found:

<<link "Begin Music box puzzle" "Music box puzzle">> <<set _timer to 180>> <<replace "#timer-display">>_timer<</replace>> <<repeat 1s>> \<<replace "#timer-display">> \<<if _timer is 1>> \<<replace "#timer-display">><</replace>><<stop>> \<<else>> \<<set _timer to _timer - 1>>_timer \<</if>> \<</replace>> \<</repeat>> <</link>>

Any help would be much appreciated!

The last bit of code isn’t showing correctly in my message, those empty <> brackets contain else, /if, /replace, /repeat and /link

Yeah, looks like you’re using the blockquote button (double quote), not the code one (which looks like </>). You should probably be able to go back and edit it to let your code show up?


Also, the #timer-display should refer to an HTML element with the ID timer-display and I don’t see where you’re defining that? So you might want a <span id="timer-display>180</span> or a <div> (also with the id)? Like in the SugarCube docs example for <<silently>>: https://www.motoslave.net/sugarcube/2/docs/#macros-macro-silently