https://github.com/ractive/pxt-interval
Interval handlers that can be unusbscribed
https://github.com/ractive/pxt-interval
makecode makecode-arcade-extensions
Last synced: 2 months ago
JSON representation
Interval handlers that can be unusbscribed
- Host: GitHub
- URL: https://github.com/ractive/pxt-interval
- Owner: ractive
- Created: 2020-05-07T19:00:06.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2020-09-01T16:23:58.000Z (almost 6 years ago)
- Last Synced: 2023-03-12T00:21:37.875Z (over 3 years ago)
- Topics: makecode, makecode-arcade-extensions
- Language: TypeScript
- Homepage: https://ractive.github.io/pxt-interval/
- Size: 502 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# pxt-interval 
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, this extension can help you. 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:
```
const unsubscribe = Interval.on(500, () => doSomething());
...
unsubscribe();
```
Here an example how to fire projectiles every 500 milliseconds for 3 seconds:
```
// Shoot for 3 seconds
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:
```
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 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.
#### Metadata
* for PXT/arcade
makeCodeRender("{{ site.makecode.home_url }}", "{{ site.github.owner_name }}/{{ site.github.repository_name }}");