Newer
Older
lostmynuts / shared / js / Engine / Utils / CountWaiter.js

var CountWaiterStatics = {};
CountWaiterStatics.CountWaiterMode = {"Simple":0,"WaitForGo":1};

class CountWaiter
{
	constructor(mode /*CountWaiter.CountWaiterMode*/)
	{
		this.callback = null;
		this.count = 0;
		this.started = false;
		this.mode = CountWaiterStatics.CountWaiterMode.Simple;
		this.param = null;
		
		if (mode !== undefined) this.mode = mode;
	}

	init(callback /*Action<T>*/, mode /*CountWaiter.CountWaiterMode*/, param /*T*/)
	{
		if (mode === undefined) mode = this.mode;
		if (param === undefined) param = null;

		this.mode = mode;
		this.callback = callback;
		this.param = param;
		this.count = 0;
		
		this.started = (mode == CountWaiterStatics.CountWaiterMode.Simple);
	}


	wait()
	{
		this.count++;
	}

	waitMany(num /*int*/)
	{
		this.count += num;
	}

	waitDone()
	{
		this.count--;
		if (this.started)
		{
			this.checkDone();
		}
	}

	checkDone()
	{
		if (this.count == 0)
		{
			var tmp = this.callback;
			var tmpParam = this.param;
			this.callback = null;
			this.param = null;
			if (tmp != null) tmp(tmpParam);
		}
	}

	go()
	{
		this.started = true;
		this.checkDone();
	}

	clear()
	{
		this.started = false;
		this.callback = null;
		this.count = 0;
		this.param = null;
	}

}