How to run some animation (like rotating a node) while doing some calculation? (multithreading?)

This is the example I want to achieve: let these 2 fragments of code run in parallel.

this.node.runAction(cc.repeatForever(cc.rotateBy(1,360));

let i = 0;
while (i < 10000000) {
cc.log(i);
}

Not sure what you’re trying to do but this might give you an idea of how to do it. I haven’t tested it, just wrote it fast. I’m sure you can figure it out! :slight_smile:

const timesInASecond = 10000000;
let i = 0;
this.node.runAction(
	cc.spawn(
		cc.rotateBy(1,360).repeatForever(),
		cc.sequence(
			cc.delayTime(1 / timesInASecond),
			cc.callFunc(() => {
				i++;
				cc.log(i)
			})
		).repeatForever()
	)
)
2 Likes

I understand the idea. Actually, I thought about this solution too, but the problem is when the calculation in callFunc is complicated then you need to save it’s state (all variables, executing point in function). In this example we stored “i” in scope outside. Another issue is we need to keep the calculation “short” enough to guarantee smooth rotation (animation).

Such calculation is not complicated enough to slow down your app’s performance, its so negligible…premature optimisation would hurt your project’s timeline.

What happens when you replace operation “i++” with implementation of searching algorithm? It does slow down performance.

Then you have to modify your calculation so you can split it into several calls. Unity coroutines are handy for that kind of things. In javascript i would go with functional programming and extensive clojure usage, like this, I hope you’ll get the idea:

initAlgorithm : function(data) {
	let i = 0;
	let limit = data;
	let worker = function(iteraions) {
		for(var j = 0; j < iterations && i < limit; j++) {
			i++;
		}
		return i >= limit;
	}
	return worker;
}

start : function() {
	this.algoWorker = this.initAlgorithm;
}

update : function(dt) {
	this.node.rotation += dt * rotationSpeed;
	var algorithmCompleted = this.algoWorker(1000);
	if(algorithmCompleted) doSomething();
}

Multithreading is the best way to solve heavy computations, but it’s not for the weak of heart :slight_smile: I don’t see any kind of multithreading support in CC and you gonna have a lot of problems on some platforms with it anyway. It’s programming, not game developing

1 Like

Thank you! Your solution is what I need now (except the last line should be like this: if(algorithmCompleted(10)) doSomething()). And we can improve to execute worker by interval of time, not only iterations.
JS is single thread, but native is multithreading. Why we can not run some task in new thread in native then return result to JS as an event?