2
\$\begingroup\$

I've been through a lot of posts over the web(and in SO) saying that it is not possible. However, I did the following code:

var a = {
	_sum: 0,
	_timer: null,
	_resetTimer: function() {
		if (this._timer) {
			window.clearTimeout(this._timer);
		}
		this._timer = window.setTimeout(this._endChain.bind(this), 0);
	},
	_endChain: function() {
		console.log(this._sum);
	},
	A: function() {
		this._resetTimer();
		this._sum+= 1;
		return this;
	},
	B: function() {
		this._resetTimer();
		this._sum+= 2;
		return this;
	}
};
a.A().B().B().A();

Demo in JsFiddle

I want to know how problematic this can be, if this is not encouraged to be used.

Edit:

A negative point is: if you need anything that would be processed by _endChain you could not use return, only with a promise or another timeout outside the whole chain. Example.

Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges201 bronze badges
asked Mar 21, 2017 at 18:24
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

It's not problematic in the sense that _endChain will always be called after the whole chain. In fact you could simplify the code by only creating the timer once:

var a = {
 _timer: null,
 _resetTimer: function() {
 if (!this._timer)
 	 this._timer = window.setTimeout(this._endChain.bind(this), 0);
 },

But the problem will come with code that follows for example:

a.A().B().B().A();
DoMoreStuff();

Most developers would be surprised to find that the first call has not completed. I think the better solution would be to implement an end method which is what many libraries do:

let result = a.A().B().B().A().end();
DoMoreStuff();

Or a promise like method:

a.A().B().B().A().then( function(result) {
 DoMoreStuff();
});
answered Mar 21, 2017 at 18:45
\$\endgroup\$
1
  • \$\begingroup\$ So it could work in case of a lone method which the rest of the code doesn't depends on. \$\endgroup\$ Commented Mar 21, 2017 at 18:54

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.