# Interval extension - interval handlers that can be unusbscribed

**URL:** https://forum.makecode.com/t/interval-extension-interval-handlers-that-can-be-unusbscribed/1998
**Category:** Show & Tell
**Tags:** extension
**Created:** [May 7, 2020, 8:07pm UTC](https://forum.makecode.com/t/interval-extension-interval-handlers-that-can-be-unusbscribed/1998 "2020-05-07T20:07:56Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![ractive](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.makecode.com/ractive/32/928_2.png) [@ractive](https://forum.makecode.com/u/ractive)
#### Post date: [May 7, 2020, 8:07pm UTC](https://forum.makecode.com/t/interval-extension-interval-handlers-that-can-be-unusbscribed/1998/1 "2020-05-07T20:07:56Z")

</div>

If you want to repeatedly do something in your game, you can add a callback method to `game.onUpdateInterval` like `game.onUpdateInterval(500, () => doSomething())` . But you cannot unsubscribe this callback from being executed - never.

If you want to do something periodically but only for a certain time, the pxt-interval extension can help you: [https://github.com/ractive/pxt-interval/](https://github.com/ractive/pxt-interval/)  
It’s a typescript-only extension and cannot be used in block mode.

A callback handler that is registered to be executed in a given interval can also be unsubscribed again. The call to `Interval.on` returns a function that can be called to do the unsubscription:

```auto
const unsubscribe = Interval.on(500, () => doSomething());
...
unsubscribe();

```

Here’s an example how to fire projectiles every 500 milliseconds for 3 seconds:

```auto
const unsubscribe = Interval.on(500, () => sprites.createProjectileFromSprite(myImage, mySprite, 50, 0));
setTimeout(() => unsubscribe(), 3000);

```

Another example that lets a spaceship shoot until it’s getting destroyed:

```auto
const spaceShip = sprites.create(someSpaceshipImage);
spaceShip.setFlag(SpriteFlag.AutoDestroy, true);

const unsubscribe = Interval.on(500, () => {
    sprites.createProjectileFromSprite(img`
    1
    1
    `, spaceShip, 0, -80);
});

spaceShip.vx = 30;
spaceShip.onDestroyed(() => unsubscribe());

```

## Using it in your project

To use this extension in your javascript project, choose “Advanced \> Extensions…” and enter `https://github.com/ractive/pxt-interval` in the search box.

This extension uses the [pxt-heap](https://github.com/jwunderl/pxt-heap) extension to easily fetch the next callback handler that should be executed.

---

<div class="post-metadata">

### Author: ![otorp2](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.makecode.com/otorp2/32/940_2.png) [@otorp2](https://forum.makecode.com/u/otorp2)
#### Post date: [May 7, 2020, 9:34pm UTC](https://forum.makecode.com/t/interval-extension-interval-handlers-that-can-be-unusbscribed/1998/2 "2020-05-07T21:34:45Z")

</div>

This is really helpful - thanks!
