0 votes
by (44.7k points)
I need to run some JavaScript code for an unknown amount of time, probably several seconds, and I'd like it to display the progress while it's working.

I've been trying to use the replace macro to update a span, with various tricks to try to trigger a display update each time.  However, my attempts to do this do not appear to cause it to update until it's all done.

What is the correct/best method in Twine/SugarCube to rapidly update the display of some text while the JavaScript is still running?

2 Answers

0 votes
by (159k points)
selected by
Best answer

You can use functions like JavaScript's document.getElementById('id-name') or jQuery's $('#id-name') from within you custom JavaScript function to access the HTML elements that makeup the current page, which then allows you to update those elements.

The following example uses Javascript to update a span element (with an ID of "counter") every 1/2 a second until the counter reaches 10.

1. Place the following within your project's Story Javascript area, it defines a count() function on the SugarCube setup object. It also uses the jQuery empty() function to remove the current content of the span element and then uses SugarCubes <jQuery>.wiki() function to add new content which can contain TwineScript markup.

setup.count = function () {
  var el = $('#counter');
  var x  = 0;
  var id = setInterval(function () {
    if (x == 10) {
    } else {
	}, 500);

2. Place the following within a Passage.

Counter: <span id="counter"></span>

<<button "Click Me">>
	<<run setup.count()>>

3. Run the story and press the "Click Me" button to see the counter update.

Obviously your custom JavaScript function will be doing something else, but you should 

0 votes
by (23.6k points)
You could just have your Javascript update the display, depending on how that is set up. Can you give us the code you are running?