I know about the ternary expression in javascript. However i don't know how to make this piece of code shorter.
if (x == false) {
x = true;
cancelAnimationFrame(BI.req);
}
else {
x = false;
BI.req = requestAnimationFrame(BI.fn.animate);
}
I guess I can make two separate functions and use them with the ternary expression. Something like this:
function cancel() {
x = true;
cancelAnimationFrame(BI.req);
}
function request() {
x = false;
BI.req = requestAnimationFrame(BI.fn.animate);
}
x == false ? cancel() : request();
But this doesn't feel like I am really making my code much shorter. Any suggestions will be much appreciated.
You can use ternary for the functions. And use ! operator to set x
x ? BI.req = requestAnimationFrame(BI.fn.animate) : cancelAnimationFrame(BI.req)
x = !x
Or even more shorter
(x = !x) ? cancelAnimationFrame(BI.req) : BI.req = requestAnimationFrame(BI.fn.animate)
The question was about shorter code so I answered this. Otherwise your own snippet is fine or consider Nina Answers because these two lines are completely non-readable.
You shouldn't use ternary operator like that too. Don't use ternary operator instead of if-else whenever there are two or move expressions in any block.
You could shorten it a bit by moving the assignment to the bottom and use a positive check.
if (x) {
BI.req = requestAnimationFrame(BI.fn.animate);
} else {
cancelAnimationFrame(BI.req);
}
x = !x;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With