1

I am trying to pause computation in javascript and interact with variables defined prior to the interrupt line.

In python, you can do this by inserting a call to interact from the code package:

import code
cat = 'cat'
pi = 3.14
def foo(bar):
    a = 3
    b = 'hello'
    code.interact(local=dict(globals(), **locals()))
    return bar

Making a call to foo in the above code would pause computation on the line with the call to interact, and you would be able to interact with the local variables a and b as well as the function arguments bar and any variables/functions within the scope of the interact (such as globally defined cat and pi variables).

I use code.interact for all my debugging in python. It's simple and lightweight. It would be great to be able to have something like code.interact in javascript, but I haven't found anything yet.

Is there something like python's code.interact function in javascript

Alnitak
  • 2,068
  • 2
  • 12
  • 24
  • Possible duplicate of [How do I debug Node.js applications?](https://stackoverflow.com/questions/1911015/how-do-i-debug-node-js-applications) – lilezek Sep 24 '17 at 19:16
  • Possible duplicate of [What is the JavaScript version of sleep()?](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep) – Obsidian Age Sep 24 '17 at 19:17
  • 1
    If your code is running in a web browser all you need is add a `debugger` statement and open your browser's developer tools. – Felix Kling Sep 24 '17 at 19:17
  • Looks like you need the `debugger` statement, works both in node and in a browser. – Wiktor Zychla Sep 24 '17 at 19:18

1 Answers1

0

In JavaScript this is called a Generator.

A generator would look something like this :

function* add(){
  const a = yield;
  const b = yield;
  console.log(`Sum is ${a + b}`);
}

const addGenerator = add();
addGenerator.next(1);
addGenerator.next(2);
// Sum is 3

The yield keyword(expression) pauses function execution, and you can place it any where in the right side of a statement.

A generator produces an iterator which you can use to run the iterator to completion.

Note though you will need the babel-pollyfill to make generators work.

Rosmarine Popcorn
  • 10,761
  • 11
  • 59
  • 89