Cancellation is cooperative. Somehow, you need to ensure that your coroutines will honor cancellation requests.

In this snippet, we replace delay() with busyWait(), a function that simply busy-waits for the desired amount of time to elapse. delay() honors cancellation; this implementation of busyWait() does not.

As a result, we see "This is executed after the busyWait(2000) call" printed in the output, even though we canceled the job prior to calling busyWait() or either println() call in the stallForTime() function. Neither println() nor busyWait() pays attention to cancellation requests, so they just keep doing their work.

You can learn more about this in:
Run Edit