Another approach is to check the isActive property of the current CoroutineScope, which will be false once the job is canceled.

Since withContext() executes its lambda expression with CoroutineScope as the receiver (this), we can simply refer to isActive to see whether our job is canceled inside of stallForTime().

You can learn more about this in:
Run Edit