N
N
Nikolai Chuprik2020-04-20 12:35:14
JavaScript
Nikolai Chuprik, 2020-04-20 12:35:14

What happens to setInterval calls if they were fired inside an object that was killed?

In the constructor, calls to some method are launched via setInterval:

function Figure()   {
     ...
     this.interval = setInterval( this.swing );
     ...
}

var fig = new Figure();


Then, after some time, I delete the corresponding object: Questions: What will happen to the asynchronous calls of the methods of the same object? Is the object really destructible?

fig = null;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2020-04-20
@choupa

To do such tricks, you will need to write a method, for example preapreDestroy:

class Some {
  constructor() {
    this.interval = setInterval(this.method, 100);
  }

  method() {
    console.log(`Date.now: ${Date.now()}`);
  }

  prepareDestroy() {
    clearInterval(this.interval);
  }
}

const sleep = duration => new Promise(resolve => setTimeout(resolve, duration));

(async () => {
  let some = new Some();

  await sleep(3000);

  some.prepareDestroy();
  some = null;
})();

Option 2: transfer setIntervaltorequestAnimationFrame

N
Nikolay Chuprik, 2020-04-20
@choupa

I realized the fallacy of the idea, because. anyway, I can’t pass the context of the object to the asynchronous function, and for this I wanted to run setInterval from the constructor. I will run setInterval not from inside the object, but in the global context, moving the necessary properties from the object to the global ones.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question