简体   繁体   中英

How to delete an Object of a function in javascript?

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM