> For the complete documentation index, see [llms.txt](https://frinn.gitbook.io/custom-machinery-1.19/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://frinn.gitbook.io/custom-machinery-1.19/mod-integrations/kubejs/recipes/function.md).

# Function

**Use one of these methods to add a function that must be processed by the machine to continue the recipe.**

Note: This has nothing to do with MC functions (or commands), this requirement allow you to make your own code in JavaScript and pass it to be executed by the machine.

```javascript
//Executed when the machine is idle and search a recipe to process.
//Returning success will allow the machine to process this recipe (if all other requirements allow it as well).
//Returning error will prevent the machine to process this recipe (the machine will keep searching for another valid recipe).
.requireFunctionToStart(ctx => {return ctx.success()})

//Executed the first tick of the crafting process.
//Returning success will allow the machine to continue to process this recipe.
//Returning error will put the machine in error status and display the provided error message.
.requireFunctionOnStart(ctx => {return ctx.success()})

//Executed each tick of the crafting process.
//Returning success will allow the machine to continue to process this recipe.
//Returning error will put the machine in error status and display the provided error message.
.requireFunctionEachTick(ctx => {return ctx.success()})

//Executed the last tick of the crafting process.
//Returning success will allow the machine to continue to process this recipe.
//Returning error will put the machine in error status and display the provided error message.
.requireFunctionOnEnd(ctx => {return ctx.success()})
```

* The passed function MUST return a Result.
* Valid results are : `ctx.success()` and `ctx.error("Error message")`
* Context has various methods for interacting with the machine, see [its wiki page](/custom-machinery-1.19/mod-integrations/kubejs/recipes/function/context.md)
* The function can be delayed, put `.delay(delay)` directly after any `.requireFunctionXXX()` call to make the function be executed at the specified delay.

### Example :

```javascript
ServerEvents.recipes(event => {
	event.recipes.custommachinery.custom_machine("custommachinery:power_crusher", 200)
	.requireFunctionEachTick(ctx => {
		var remaining = ctx.machine.addItemToSlot("output1", Item.of("minecraft:diamond", 2), true);

		if(remaining.count == 0) {
                        ctx.machine.addItemToSlot("output1", Item.of("minecraft:diamond", 2), false);
			return ctx.success();
                }
		return ctx.error("Can't add 2 diamonds in output slot");
	})
})
```
