Skip to content

Create a Live Coding Music App · Part 11 of 18 in the series

Part 11: When the Code Is Wrong

Catch every mistake the code can make: options are checked against the schema with a "did you mean", an error is marked at its line in the editor, and a worker with a timeout ends code that never ends. The music plays on through all of it.

Quest objectives

  • Check the options against the schema and suggest the closest name
  • Find the line of an error in the stack trace of code made with new Function
  • Ask the parser of the editor where a syntax error is
  • Mark the line in the editor and show the message under it
  • Run the code in a worker and end it after 3 seconds
  • Show what the code logs with console.log

Whoever changes code while it plays makes mistakes while it plays. The app of part 10 already survives most of them: if a run fails, the last patch plays on. But it says little about what went wrong, and one kind of mistake still takes the whole page down:

  • monoSynth({ cutof: 900 }) is no error at all. The script only reads the options it knows, so the misspelled one is dropped and the cutoff stays at 300. You hear no change and get no hint why.

  • kitt.to(out) gives kitt is not defined in the status line, but not the line it is in.

  • while (true) {} never comes back. The page freezes, the clock can no longer schedule, the music runs out after the tenth of a second that was scheduled ahead, and no button works.

This part gives every mistake a message and, where there is one, a line. And it makes sure that none of them stops the music.

Check the options

The schema of part 9 knows everything about an option: its name, whether it is a number or a text, its range, the words it can be. Until now it only supplied the defaults. From now on the script checks what the code gives against it. Most of src/script.ts changes, so replace the file. It comes in five blocks that follow one another in the file, with a blank line between them. The first is the head of the file:

src/script.ts
import { mini, MiniError } from './mini.ts';
import type { Options, Patch, Value } from './patch.ts';
import { OUT, UNITS, type UnitType } from './schema.ts';

/** What a run of the code comes to: a patch, or the reason why there is none. */
export type Outcome =
  | { ok: true; patch: Patch; logs: string[] }
  | { ok: false; message: string; line: number | undefined; logs: string[] };

/** A mistake in the code that we found, as opposed to one JavaScript found. */
export class ScriptError extends Error {}

/** What the code holds in its variables: a unit of the patch, which can be connected. */
class Handle {
  readonly id: string;
  readonly type: string;
  private readonly spec: UnitType;
  private readonly patch: Patch;

  constructor(id: string, type: string, spec: UnitType, patch: Patch) {
    this.id = id;
    this.type = type;
    this.spec = spec;
    this.patch = patch;
  }

  /** Connects this unit to another one. Gives back the other one, so that calls can be chained. */
  to(target: Handle): Handle {
    if (!(target instanceof Handle)) throw new ScriptError(`${this.type}.to() needs something to connect to, such as out`);
    const gives = this.spec.gives;
    const takes = target.spec.takes;
    if (!gives) throw new ScriptError(`${this.type} has no output`);
    if (gives !== takes) {
      throw new ScriptError(`${this.type} gives ${gives}, but ${target.type} ${takes ? `takes ${takes}` : 'has no input'}`);
    }
    this.patch.cables.push({ from: this.id, to: target.id, kind: gives });
    return target;
  }
}

Handle is the one of part 9. New is Outcome: what a run of the code comes to. Until now runScript() gave back a patch or threw an error. From now on it never throws. It gives back either a patch or a message with a line, and in both cases what the code logged. The reason comes at the end of this part: the result will have to travel from a worker to the page, and plain data travels best.

A misspelled name deserves more than "unknown option". The second block finds the word that was probably meant:

src/script.ts
// ---------------------------------------------------------------------------
// Checking the options

/** How many letters have to be changed, added or removed to turn one word into another. */
function distance(a: string, b: string): number {
  let row = Array.from({ length: b.length + 1 }, (_, index) => index);
  for (let i = 1; i <= a.length; i += 1) {
    const next = [i];
    for (let j = 1; j <= b.length; j += 1) {
      next[j] = Math.min(row[j] + 1, next[j - 1] + 1, row[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
    }
    row = next;
  }
  return row[b.length];
}

/** " Did you mean cutoff?", if one of the words is close to what was written. */
function didYouMean(word: string, words: readonly string[]): string {
  const typed = word.toLowerCase();
  const [best] = words
    // A word that starts with what was typed is as close as it gets: "saw" means "sawtooth".
    .map((candidate) => ({
      candidate,
      far: candidate.toLowerCase().startsWith(typed) ? 0 : distance(typed, candidate.toLowerCase()),
    }))
    .sort((a, b) => a.far - b.far);
  return best && best.far <= Math.max(2, word.length / 3) ? ` Did you mean ${best.candidate}?` : '';
}

distance() counts how many single letters have to be changed, added or removed to turn one word into the other. From cutof to cutoff it is 1. This number is called the edit distance. The function works through a table with a row per letter of the first word and a column per letter of the second. A cell holds the distance between the two beginnings of the words up to there, and it is the cheapest of three ways to reach it:

  • remove a letter: the cell above, plus 1 (row[j] + 1)

  • add a letter: the cell to the left, plus 1 (next[j - 1] + 1)

  • go on in both words: the cell above and to the left, plus 1 if the two letters differ (row[j - 1] + …)

The answer is the last cell of the last row. A row only needs the row above it, so the function keeps two rows instead of the table.

didYouMean() measures every candidate and takes the closest. One case gets ahead of the count: a candidate that begins with what was typed has a distance of 0. saw is five letters away from sawtooth, and still nothing else can be meant. The closest word is only suggested if it is close: at most 2 changes, or a third of the length of the typed word if that is more. Nothing is suggested for wave: 'noise'.

The third block is the check itself:

src/script.ts
/** The options of a unit: what the code gave, checked against the schema, on top of the defaults. */
function readOptions(type: string, spec: UnitType, given: unknown): Options {
  if (given !== undefined && (typeof given !== 'object' || given === null)) {
    throw new ScriptError(`${type}() takes its options in braces, like ${type}({ volume: 0.5 })`);
  }
  const names = Object.keys(spec.options);
  for (const name of Object.keys(given ?? {})) {
    if (!names.includes(name)) throw new ScriptError(`${type} has no option "${name}".${didYouMean(name, names)}`);
  }

  const options: Options = {};
  for (const [name, option] of Object.entries(spec.options)) {
    const value = (given as Record<string, unknown> | undefined)?.[name];
    options[name] = value === undefined ? option.default : readValue(`${name} of ${type}`, option, value);
  }
  return options;
}

function readValue(what: string, option: UnitType['options'][string], value: unknown): Value {
  if (typeof option.default === 'number') {
    if (typeof value !== 'number' || Number.isNaN(value)) {
      throw new ScriptError(`${what} needs a number, but got ${JSON.stringify(value)}`);
    }
    // A number outside its range is moved to the nearest end of it.
    return Math.min(option.max ?? Infinity, Math.max(option.min ?? -Infinity, value));
  }
  if (typeof value !== 'string') throw new ScriptError(`${what} needs a text, but got ${JSON.stringify(value)}`);
  if (option.choices && !option.choices.includes(value)) {
    throw new ScriptError(
      `${what} can be ${option.choices.join(', ')}, but not "${value}".${didYouMean(value, option.choices)}`,
    );
  }
  return value;
}

readOptions() asks three things. Are the options an object at all: monoSynth(300) is answered with monoSynth() takes its options in braces, like monoSynth({ volume: 0.5 }). Is every name one the schema lists: if not, the message is monoSynth has no option "cutof". Did you mean cutoff?. And does every value fit, which is the job of readValue().

The schema has no field for the type of an option. Its default says it: an option whose default is a number takes numbers. A text where a number belongs gives cutoff of monoSynth needs a number, but got "high". A number outside its range is no error. It is moved to the nearest end of the range, so cutoff: 20000 becomes 8000. While you play, a value that is too high should not cost you the run. A text has to be one of the choices, if the schema lists any: wave of monoSynth can be sawtooth, square, triangle, sine, but not "saw". Did you mean sawtooth?

All of these are thrown as ScriptError, like the mistakes that to() finds since part 9, such as drums gives audio, but drums takes notes for kit.to(kit). A ScriptError is a message written for whoever is typing the song. It is shown as it is.

Find the line

A message says what is wrong. In a song of thirty lines you also want to know where. Every error carries a stack: a text that lists the functions that were running when the error was made, the innermost first, each with its file, line and column. The code of the editor ran as a function made with new Function, which has no file. Chrome writes <anonymous> in its place, so the entry of the editor's code has this in it: <anonymous>:9:14. Line 9, column 14. The fourth block reads that number:

src/script.ts
// ---------------------------------------------------------------------------
// Finding the line of an error

/** The line and column that a stack trace gives for code made with `new Function`. */
const FRAME = /(?:<anonymous>|> Function):(\d+):\d+/;

function frameLine(error: unknown): number | undefined {
  const frame = FRAME.exec(error instanceof Error ? (error.stack ?? '') : '');
  return frame ? Number(frame[1]) : undefined;
}

/**
 * The number an engine gives the first line of a function's body. The engines put a
 * different number of lines in front of it, so we ask: an error in a body's first line.
 */
const FIRST_LINE = (() => {
  try {
    new Function('throw new Error()')();
  } catch (error) {
    return frameLine(error);
  }
  return undefined;
})();

/** The line of the code in which an error happened, counted from 1. */
function lineOf(error: unknown): number | undefined {
  const line = frameLine(error);
  return line === undefined || FIRST_LINE === undefined ? undefined : line - FIRST_LINE + 1;
}

The regular expression FRAME looks for <anonymous>: or > Function:, followed by two numbers with a colon between them, and keeps the first number, the line. The first form is Chrome's. The second is meant for Firefox and is untested: this series was only tried in Chrome. Where the search finds nothing, the message is shown without a line.

exec() gives the first match, and the stack lists the innermost function first. An error thrown by readOptions() has entries of the project's own files on top. Those carry the address of a file where the expression wants <anonymous>, so the first match is the line of the editor's code that made the call. That is the line you want: the one with monoSynth({ cutof: 300 }) in it.

The number is not the line in the editor yet. To make a function out of a text, the browser's JavaScript engine writes the head of a function in front of it, and the head takes up lines of its own. In Chrome the first line of the body counts as line 3. It would be quick to subtract 2, but the engine of another browser may put a different number of lines in front, and then every mark would sit in the wrong line.

So FIRST_LINE is measured, not assumed. When the file is loaded, it makes a function whose body throws an error in its first line, and reads the line from the stack of that error. Whatever number comes out is the number this JavaScript engine gives to line 1. lineOf() subtracts it: an error that Chrome reports in line 9 is in line 9 − 3 + 1 = 7 of the editor. The words "use strict"; that runScript() puts in front of the code stand in the same line as the code's first line, so they don't shift anything.

If the stack has no such entry, lineOf() gives undefined, and the message is shown without a line.

Run the code, catch everything

The fifth and last block runs the code:

src/script.ts
// ---------------------------------------------------------------------------
// Running the code

/** Turns a value into the text `console.log` shows for it. */
function show(value: unknown): string {
  if (typeof value === 'string') return value;
  if (value instanceof Handle) return `[${value.id}]`;
  try {
    return JSON.stringify(value) ?? String(value);
  } catch {
    return String(value);
  }
}

/** Runs the code and gives back the patch it describes. Never throws. */
export function runScript(code: string): Outcome {
  const patch: Patch = { bpm: 120, units: [], cables: [] };
  const counts: Record<string, number> = {};
  const logs: string[] = [];

  /** Adds a unit to the patch. */
  function create(type: string, given: unknown): Handle {
    const spec = UNITS[type];
    const options = readOptions(type, spec, given);
    counts[type] = (counts[type] ?? 0) + 1;
    const id = `${type}${counts[type]}`;
    patch.units.push({ id, type, options });
    return new Handle(id, type, spec, patch);
  }

  /** Everything the code can use, by name. */
  const api: Record<string, unknown> = {
    out: new Handle('out', 'out', OUT, patch),
    bpm(value: unknown) {
      if (typeof value !== 'number' || Number.isNaN(value)) {
        throw new ScriptError(`bpm() needs a number, but got ${JSON.stringify(value)}`);
      }
      patch.bpm = Math.min(240, Math.max(40, value));
    },
    // The code's own console: what it logs is shown on the page.
    console: {
      log(...values: unknown[]) {
        if (logs.length < 100) logs.push(values.map(show).join(' '));
      },
    },
  };
  for (const type of Object.keys(UNITS)) api[type] = (options?: unknown) => create(type, options);

  // A pattern takes its text first. Reading it here finds mistakes before anything plays.
  api.pattern = (source: unknown, options?: unknown) => {
    if (typeof source !== 'string') throw new ScriptError(`pattern() needs its notes as a text, like pattern('bd sd')`);
    try {
      mini(source);
    } catch (error) {
      if (error instanceof MiniError) throw new ScriptError(`${error.message} at character ${error.position + 1} of "${source}"`);
      throw error;
    }
    const handle = create('pattern', options);
    patch.units[patch.units.length - 1].options.source = source;
    return handle;
  };

  try {
    // The code becomes the body of a function whose parameters are the names of the API.
    const run = new Function(...Object.keys(api), `"use strict";${code}`);
    run(...Object.values(api));
    return { ok: true, patch, logs };
  } catch (error) {
    const message = error instanceof ScriptError ? error.message : String(error);
    return { ok: false, message, line: lineOf(error), logs };
  }
}

Compared to part 9, four things are different.

  • create() gets its options from readOptions(), which throws before the unit is added if something is wrong with them.

  • bpm() and pattern() insist on what they need. bpm('fast') used to become 120 without a word, and now gives bpm() needs a number, but got "fast". The text of a pattern is no longer mixed into the options before they are checked. It is written into the unit after create() made it.

  • The code gets a console of its own. It is an entry of the API like the others, and so becomes a parameter of the function, which hides the browser's console of the same name. Its log() collects up to 100 lines. show() turns each value into text: a text stays as it is, a unit becomes its id in brackets, anything else becomes JSON. So console.log(bass) shows [monoSynth1], the id the engine of part 10 knows the bass by.

  • Making the function and calling it are wrapped in one try. Whatever goes wrong ends up as an Outcome. A ScriptError gives its message as it is. Any other error is one that JavaScript found, and String(error) puts its name in front: ReferenceError: kitt is not defined.

Syntax errors

One kind of mistake has no line in its stack. If the code is not JavaScript at all, say because a bracket is missing, new Function itself throws a SyntaxError, before any line of the code ran. No function of the code was running, so the stack has no entry for it. In Chrome the stack only says at new Function (<anonymous>), without numbers, and FRAME finds nothing. The message says what JavaScript expected, but not where.

The editor knows where. CodeMirror colors the code with a parser of its own, and that parser is made for code that is being typed, which is broken most of the time. Where the text doesn't fit the language, it puts an error node into its tree and reads on. The first error node is the place.

Two more packages of CodeMirror give access to the tree and to marks in the text. Both are in node_modules already, because the editor is made of them. Installing them by name writes them into package.json, so the project doesn't lean on packages it never asked for:

~/loopcode
$ npm install @codemirror/language @codemirror/lintup to date, audited 37 packages in 443ms

In src/editor.ts, add two functions at the end of the file. They need two imports below the one of javascript: ensureSyntaxTree from @codemirror/language, and setDiagnostics and the type Diagnostic from @codemirror/lint:

src/editor.ts
/** Underlines a line of the code and shows the message on it. Without a line, takes the mark away. */
export function markError(view: EditorView, message?: string, line?: number) {
  const diagnostics: Diagnostic[] = [];
  if (message !== undefined && line !== undefined && line >= 1 && line <= view.state.doc.lines) {
    const { from, to } = view.state.doc.line(line);
    diagnostics.push({ from, to, severity: 'error', message });
  }
  view.dispatch(setDiagnostics(view.state, diagnostics));
}

/**
 * The line of the first place where the code isn't JavaScript. The editor's own parser
 * knows: it reads on after a mistake and leaves a mark in its tree.
 */
export function syntaxErrorLine(view: EditorView): number | undefined {
  const tree = ensureSyntaxTree(view.state, view.state.doc.length, 500);
  let position: number | undefined;
  tree?.iterate({
    enter(node) {
      if (position !== undefined) return false;
      if (node.type.isError) position = node.from;
      return undefined;
    },
  });
  return position === undefined ? undefined : view.state.doc.lineAt(position).number;
}

A diagnostic is CodeMirror's word for a remark on a stretch of the text: where it begins and ends, how bad it is, and a message. setDiagnostics() replaces all of them at once. With one in the list, the line is underlined in red, and the message appears when the mouse rests on it. An empty line has nothing to underline and gets a small red mark at its start instead. With an empty list, the mark goes away. The line is checked against the length of the text first, because doc.line() throws for a line that doesn't exist.

syntaxErrorLine() asks for the tree. The editor only parses as far as it has to, so ensureSyntaxTree() tells it to finish up to the end of the text, and gives it half a second for that. iterate() walks through the tree and calls enter for every node. The first node whose type is an error gives the position, and false keeps the walk from going deeper after that.

A worker with a timeout

That leaves the loop that never ends. It throws no error that could be caught. The JavaScript of a page runs on a single thread, and that thread also handles the clicks and the timer of the clock. A loop that doesn't end never hands it back, and the page has no way of stopping code that is running.

A worker is a second thread: a script that runs beside the page, with no access to the page, and talks to it only through messages. And a worker can be ended from outside, with terminate(), whatever it is doing. So the code of the editor moves into a worker. The page waits for the answer, and if none comes within 3 seconds, it ends the worker.

This works because of a decision of part 9: running the code makes no sound. It gives a patch, and a patch is plain data, which can be sent as a message. The worker needs no audio and no page. Create src/worker.ts:

src/worker.ts
import { runScript, type Outcome } from './script.ts';

export interface Request {
  id: number;
  code: string;
}

export type Reply = Outcome & { id: number };

// A worker has no page: all it does is run the code it is sent, and send back what came of it.
self.addEventListener('message', (event: MessageEvent<Request>) => {
  const reply: Reply = { ...runScript(event.data.code), id: event.data.id };
  self.postMessage(reply);
});

The worker imports src/script.ts, and with it the parser of the patterns and the schema. From now on the code of the editor runs here, and FIRST_LINE is measured here too, in the place where the code runs. Every request carries a number, and the answer carries it back, so the page knows which run an answer belongs to.

The counterpart runs in the page. Create src/runner.ts:

src/runner.ts
import type { Outcome } from './script.ts';
import type { Reply, Request } from './worker.ts';

/** Longer than any song's code takes. Whatever runs longer is most likely an endless loop. */
const TIMEOUT = 3000;

let worker: Worker | undefined;
let lastId = 0;
const waiting = new Map<number, (outcome: Outcome) => void>();

function getWorker(): Worker {
  if (!worker) {
    worker = new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' });
    worker.addEventListener('message', (event: MessageEvent<Reply>) => {
      const { id, ...outcome } = event.data;
      waiting.get(id)?.(outcome);
    });
  }
  return worker;
}

/** Runs the code away from the page, in a worker. Always answers, even if the code never ends. */
export function run(code: string): Promise<Outcome> {
  lastId += 1;
  const id = lastId;
  return new Promise((resolve) => {
    const timer = window.setTimeout(() => {
      // The only way to stop code that doesn't end: end the worker it runs in. The next
      // run starts a new one.
      worker?.terminate();
      worker = undefined;
      const seconds = TIMEOUT / 1000;
      for (const answer of waiting.values()) {
        answer({
          ok: false,
          message: `The code ran for more than ${seconds} seconds and was stopped. Is there a loop that never ends?`,
          line: undefined,
          logs: [],
        });
      }
    }, TIMEOUT);

    waiting.set(id, (outcome) => {
      window.clearTimeout(timer);
      waiting.delete(id);
      resolve(outcome);
    });
    const request: Request = { id, code };
    getWorker().postMessage(request);
  });
}

new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' }) is the form Vite looks for: it finds the file and builds the worker as a script of its own. The worker is made at the first run and kept for the next ones.

run() gives back a promise. It puts a function into waiting under the number of the request, starts a timer of 3 seconds and sends the code off. If the answer comes, the function stops the timer and resolves the promise. If the timer comes first, it ends the worker, forgets it, and answers everything that is waiting with a message of its own: The code ran for more than 3 seconds and was stopped. Is there a loop that never ends? The next run finds no worker and starts a new one.

Show it on the page

The page has to wait for the worker now, so run() and start() become async, and the result is an Outcome instead of a patch or an error. Replace src/main.ts with:

src/main.ts
import { audio } from './audio.ts';
import { createEditor, markError, syntaxErrorLine } from './editor.ts';
import { Engine } from './engine.ts';
import { run as runCode } from './runner.ts';
import { SONG } from './song.ts';
import './style.css';

const engine = new Engine();

const play = document.querySelector<HTMLButtonElement>('#play')!;
const status = document.querySelector<HTMLElement>('#status')!;
const bpm = document.querySelector<HTMLSpanElement>('#bpm')!;

/** Runs the code in the editor. If it fails, what was playing plays on. */
async function run(): Promise<boolean> {
  const outcome = await runCode(editor.state.doc.toString());
  const lines = [...outcome.logs];
  if (outcome.ok) {
    const { kept, created, removed } = engine.apply(outcome.patch);
    bpm.textContent = String(outcome.patch.bpm);
    lines.push(`${outcome.patch.units.length} units: ${kept} kept, ${created} new, ${removed} removed`);
    markError(editor);
  } else {
    // JavaScript doesn't say where code is that it couldn't read at all. The editor does.
    const line = outcome.line ?? syntaxErrorLine(editor);
    lines.push(line === undefined ? outcome.message : `Line ${line}: ${outcome.message}`);
    markError(editor, outcome.message, line);
  }
  status.textContent = lines.join('\n');
  status.classList.toggle('error', !outcome.ok);
  status.scrollTop = status.scrollHeight;
  return outcome.ok;
}

async function start() {
  void audio().resume();
  if (!engine.clock.playing && (await run())) engine.start();
  showPlaying();
}

function stop() {
  engine.stop();
  showPlaying();
}

function showPlaying() {
  play.textContent = engine.clock.playing ? '■ Stop' : '▶ Play';
  play.classList.toggle('on', engine.clock.playing);
}

const editor = createEditor(document.querySelector<HTMLElement>('#editor')!, SONG, {
  // Ctrl+Enter starts the music, or runs the changed code while it plays.
  run: () => void (engine.clock.playing ? run() : start()),
  stop,
});

play.addEventListener('click', () => void (engine.clock.playing ? stop() : start()));
document.querySelector<HTMLButtonElement>('#run')!.addEventListener('click', () => {
  void (engine.clock.playing ? run() : start());
});

/** Shows where the music is, as bar.beat, once per frame. */
const position = document.querySelector<HTMLSpanElement>('#position')!;
function draw() {
  const { clock } = engine;
  const cycle = clock.playing ? Math.max(0, clock.cycleAt(audio().currentTime)) : 0;
  position.textContent = `${Math.floor(cycle) + 1}.${Math.floor((cycle % 1) * 4) + 1}`;
  requestAnimationFrame(draw);
}
draw();

run() collects the lines for the bar under the editor: first what the code logged, then the result. If the run was good, the patch goes to the engine as before, and markError(editor) without a message takes an old mark away. If it was not, engine.apply() is not called, and what was playing plays on. The line comes from the script, and if the script has none, from the editor's parser. With a line, the message is shown as Line 7: …, and the line is marked in the code.

The callers don't wait for the promise. The void in front of the calls says that this is meant.

The bar can hold several lines now. In src/style.css, replace the rule for .status:

src/style.css
.status {
  min-height: 2.2em;
  max-height: 6.4em;
  overflow-y: auto;
  padding: 6px 12px;
  background: var(--night);
  border-top: 2px solid var(--edge);
  color: var(--muted);
  white-space: pre-wrap;
}

It grows to about four lines and scrolls after that. run() scrolls it to the end, so the result is always in view, below whatever the code logged.

Try it

Press Play and break the song while it plays. After every change, press Ctrl+Enter. The music plays on each time.

  • Change cutoff in line 7 to cutof. The bar shows Line 7: monoSynth has no option "cutof". Did you mean cutoff?, and line 7 is underlined. Put the letter back and run the code: the mark is gone, and the bar shows the counts of part 10 again.

  • Write cutoff: 'high': Line 7: cutoff of monoSynth needs a number, but got "high".

  • Write cutoff: 20000. No error: the filter of the bass rests as high as the range allows, at 8000 hertz.

  • Change line 5 to kit.to(kit): Line 5: drums gives audio, but drums takes notes. Change it back.

  • Delete the last bracket of a line. The bar shows a SyntaxError, with a line that the editor's parser found. Put the bracket back.

  • With the song in order again, add console.log(bass) as a last line. [monoSynth1] appears above the result.

  • Add while (true) {} as a last line. For three seconds nothing happens, except that the music plays on and the counter in the header keeps counting. Then the bar shows The code ran for more than 3 seconds and was stopped. Is there a loop that never ends? Remove the loop and run the code again: it works as before.

Press Play, then break the code: misspell an option, delete a bracket, or add while (true) {} as a last line, and press Ctrl+Enter. The music plays on, and the line under the editor says what is wrong.
Open in a new tab

Comments

The comments are GitHub Discussions: sign in with GitHub to write one.

The comments come from GitHub, through giscus. Loading them sends your IP address to giscus.app and GitHub.