What's the proper way to document callbacks with jsdoc?
JSDoc 3 has a @callback tag for exactly this purpose. Here's a usage example:
/**
* Callback for adding two numbers.
*
* @callback addStuffCallback
* @param {int} sum - An integer.
*/
/**
* Add two numbers together, then pass the results to a callback function.
*
* @param {int} x - An integer.
* @param {int} y - An integer.
* @param {addStuffCallback} callback - A callback to run.
*/
function addStuff(x, y, callback) {
callback(x+y);
}
Another possibility is to describe the value passed to the callback this way:
/**
* Add two numbers together, then pass the results to a callback function.
*
* @function addStuff
* @param {int} x - An integer.
* @param {int} y - An integer.
* @param {function(int)} callback - A callback to run whose signature is (sum), where
* sum is an integer.
*/
function addStuff(x, y, callback) {
callback(x+y);
});
To document the return type of the callback, use @param {function(int):string}
.
Workaround to make VSCode understand it
/**
* @typedef {function(FpsInfo)} fpsCallback
* @callback fpsCallback
* @param {FpsInfo} fps Fps info object
*/
/**
* @typedef {Object} FpsInfo
* @property {number} fps The calculated frames per second
* @property {number} jitter The absolute difference since the last calculated fps
* @property {number} elapsed Milliseconds ellapsed since the last computation
* @property {number} frames Number of frames since the last computation
* @property {number} trigger Next computation will happen at this amount of frames
*/
/**
* FPS Meter - Returns a function that is used to compute the framerate without the overhead of updating the DOM every frame.
* @param {fpsCallback} callback Callback fired every time the FPS is computed
* @param {number} [refreshRate=1] Refresh rate which the fps is computed and the callback is fired (0 to compute every frame, not recommended)
* @returns {function} Returns a function that should be called on every the loop tick
* @author Victor B - www.vitim.us - github.com/victornpb/fpsMeter
*/
function createFpsMeter(callback, refreshRate = 1) {
// ...
}