0

For example, the variable x is an object of the function my. I only want the function my to run for a period of time but I don't know how to stop it.

function my (num){
  while (1) // means this process is an infinite loop
  {
    console.log(1);
  }
}

var x = new my();

In the premise of not modifying the function my(because the origin function is very complex), how to stop the function, or how to delete the object?

2
  • 2
    You always need a condition that describes when something should stop. Do you know in advance how many seconds the function should run? Is the a finite amount of times it should run? Is there a certain state the object should reach and then stop? Without more details, we cannot really say what would be applicable in this situation without knowing actually what is happening and how/why/when it should stop. So it kinda sounds like a structural or architecture issue. If someone gave you code with a while(1) without an exit, you probably cannot do anything without changing that while loop. Commented Apr 18, 2019 at 12:48
  • I just want to mean that the function will keep running as long as it was started. The oringin function doesn't have such while(1) loop which will effect other functions to work, I just want to know is there a way to stop the function without changing the function. Commented Apr 19, 2019 at 0:26

1 Answer 1

4

You can't. There is no kind of concurrency in JS, therefore you cannot concurrently stop another action. You have to modify the blocking code to support cooperative concurrent cancellations.

 const tick = () => new Promise(res => setTimeout(res, 0));

 let kill;

 function my (num){
  (async function() {
    while (!kill) {
      console.log(1);
      await tick();
     }
  })();
}

var x = new my();

setTimeout(() => kill = true, 10000);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.