I read libraries tutorial and have a question about Example of async function for callback and preload(). I followed its code and wrote an example.
p5.prototype.loadXXX = function(callback) {
const ret = {};
setTimeout(() => {
const data = {
x: 1,
y: 2
};
for (let prop in data) {
ret[prop] = data[prop];
}
if (typeof callback == 'function') {
callback(ret); // do the callback.
}
}, 1000);
return ret;
};
p5.prototype.registerPreloadMethod('loadXXX', p5.prototype);
When calling loadXXX
in preload
, the canvas only show “Loading…”. I looked into those loadXXX
function in the p5.js source, they all call self._decrementPreload()
. I tried to rewrite my code.
p5.prototype.loadXXX = function(callback) {
const ret = {};
const self = this;
setTimeout(() => {
const data = {
x: 1,
y: 2
};
console.log('Timeout');
for (let prop in data) {
ret[prop] = data[prop];
}
if (typeof callback == 'function') {
callback(ret); // do the callback.
}
self._decrementPreload();
}, 1000);
return ret;
};
p5.prototype.registerPreloadMethod('loadXXX', p5.prototype);
It works. I use p5.js 1.1.9. Is self._decrementPreload()
an official way to do that? Does the doc require an update?