How to avoid unexpected behavior caused by later, schedule etc. deferred execution methods?

The methods like later, schedule etc are often used to run code from external libraries etc especially in the context of discourse.

The problem is, these can cause some side effects in some cases. Let’s take an example of the voice recording plugin,

The goal was to stop the recording at 3 minutes even if the user hasn’t stopped the recording process.

I simply set later starting from when the recording starts and executes stopRecording at 3 minutes.

But let’s say the user explicitly stops the recording and they start the recording again, so again later is called which will run 3 minutes from now.

All well and good till now.

But what happens is, this time the recording stops some time before the 3 minutes.

The reason being, the previous call later was still around in the memory which ran.

How to rectify this?

Thanks to ember, we can unschedule these functions, but for that we need to have a reference to that call.

When you call one of these functions, save the reference to them like this,

let abc = later(()=>{bla bla}, 1000);
this.set('ref', abc);

now let’s suppose the case occurs when you need to unschedule this execution. Do


The import for the cancel function

import { cancel } from "@ember/runloop";