Results 1 to 3 of 3

Thread: Pass code to function by parameter

  1. #1
    Join Date
    Mar 2011
    Posts
    2,144
    Thanks
    59
    Thanked 116 Times in 113 Posts
    Blog Entries
    4

    Default Pass code to function by parameter

    Hey everyone,

    Code:
      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.
    Last edited by keyboard; 03-07-2012 at 04:33 AM.

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    actions is an object:

    Code:
    {
        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:

    Code:
    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:

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

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Mar 2011
    Posts
    2,144
    Thanks
    59
    Thanked 116 Times in 113 Posts
    Blog Entries
    4

    Default

    This really helped, thanks!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •