PDA

View Full Version : Resolved Pass code to function by parameter



keyboard
03-06-2012, 09:47 PM
Hey everyone,




function setTimer( remain, actions ) {
(function countdown() {
display("countdown", toMinuteAndSecond(remain));
actions[remain] && actions[remain]();
(remain -= 1) >= 0 && setTimeout(arguments.callee, 1000);
})();
}

setTimer(userInput, {
10: function () { display("notifier", "Just 10 seconds to go"); },
5: function () { display("notifier", "5 seconds left"); },
0: function () { display("notifier", "Time is up"); }
});


When this code calls the function setTimer(), the second parameter is all that code.
What are they doing with all 10: 5: and 0: and how does actions[remain] && actions[remain](); work?
I'm sorry if I wasn't clear.

jscheuer1
03-07-2012, 04:19 AM
actions is an object:



{
10: function () { display("notifier", "Just 10 seconds to go"); },
5: function () { display("notifier", "5 seconds left"); },
0: function () { display("notifier", "Time is up"); }
}

remain is expected to be a number, potentially one of the keys (10, 5, or, 0) in the action object.

actions[remain] is the first half of an && statement is used there as a boolean. There either is one or there isn't. If it is there however, it's expected to be a function. If there is then (&&) it's executed:


actions[remain]();

If it's not there, the first part of the && statement is false, so the second part isn't considered.

So let's say remain started as 10. This would be true and would execute:


10: function () { display("notifier", "Just 10 seconds to go"); },

keyboard
03-07-2012, 04:33 AM
This really helped, thanks!