0 votes
by (38.6k 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 (154k 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) {
      clearInterval(id);
    } else {
      x++; 
      el.empty().wiki(x);
    }
	}, 500);
};

2. Place the following within a Passage.

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

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

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?
Welcome to Twine Q&A, where you can ask questions and receive answers from other members of the community.

You can also find hints and information on Twine on the official wiki and the old forums archive.

See a spam question? Flag it instead of downvoting. A question flagged enough times will automatically be hidden while moderators review it.
...