firefox global variables woes

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • inigo.villalba@gmail.com

    firefox global variables woes

    Hi,
    I hope someone can point out my error because I'm starting to lose my
    hair over this. It's probably a very straigh forward error but after
    only 4 hours sleep it's doing my head in. It's to do with global
    variables in Firefox 1.

    The following code works no problems and generates a whole bunch of
    numbers

    <script type="text/javascript">


    function createCal(){
    var dateObj = new Date();


    for(var i=0;i<32;i++){
    date = dateObj.getDate ();

    set_date = dateObj.setDate (i);
    document.write( date);

    }

    }
    </script>

    but when I try to place the dateObj variable outside the function (with
    or without the preceding "var") it tells me dateObj is not defined.
    Aren't variables declared outside of a function supposed to be global?
    It all works fine in IE 5 btw

    <script type="text/javascript">

    var dateObj = new Date();
    function createCal(){



    for(var i=0;i<32;i++){
    date = dateObj.getDate ();

    set_date = dateObj.setDate (i);
    document.write( date);

    }

    }
    </script>

    Interestingly when I replace the document.write( ) with an alert
    everything works as it should.

    Thanks

    barabis

  • Lee

    #2
    Re: firefox global variables woes

    inigo.villalba@ gmail.com said:
    [color=blue]
    >but when I try to place the dateObj variable outside the function (with
    >or without the preceding "var") it tells me dateObj is not defined.
    >Aren't variables declared outside of a function supposed to be global?
    >It all works fine in IE 5 btw
    >
    ><script type="text/javascript">
    >
    >var dateObj = new Date();
    >function createCal(){
    >
    >
    >
    > for(var i=0;i<32;i++){
    > date = dateObj.getDate ();
    >
    > set_date = dateObj.setDate (i);
    > document.write( date);
    >
    > }
    >
    >}
    ></script>
    >
    >Interestingl y when I replace the document.write( ) with an alert
    >everything works as it should.[/color]

    It's a matter of how/when your function createCal() is being called.
    If it's called after the page has been rendered, the first invocation
    of document.write( ) clears the current page, destroying your global
    variables.

    Comment

    • barabis

      #3
      Re: firefox global variables woes

      It's funny that it doesnt affect IE. No wonder a lot of the dhtml calendars
      don't work in firefox tho.
      "Lee" <REM0VElbspamtr ap@cox.net> wrote in message
      news:cuct9u01bs r@drn.newsguy.c om...[color=blue]
      > inigo.villalba@ gmail.com said:
      >[color=green]
      >>but when I try to place the dateObj variable outside the function (with
      >>or without the preceding "var") it tells me dateObj is not defined.
      >>Aren't variables declared outside of a function supposed to be global?
      >>It all works fine in IE 5 btw
      >>
      >><script type="text/javascript">
      >>
      >>var dateObj = new Date();
      >>function createCal(){
      >>
      >>
      >>
      >> for(var i=0;i<32;i++){
      >> date = dateObj.getDate ();
      >>
      >> set_date = dateObj.setDate (i);
      >> document.write( date);
      >>
      >> }
      >>
      >>}
      >></script>
      >>
      >>Interesting ly when I replace the document.write( ) with an alert
      >>everything works as it should.[/color]
      >
      > It's a matter of how/when your function createCal() is being called.
      > If it's called after the page has been rendered, the first invocation
      > of document.write( ) clears the current page, destroying your global
      > variables.
      >[/color]


      Comment

      • RobG

        #4
        Re: firefox global variables woes

        inigo.villalba@ gmail.com wrote:[color=blue]
        > Hi,
        > I hope someone can point out my error because I'm starting to lose my
        > hair over this. It's probably a very straigh forward error but after
        > only 4 hours sleep it's doing my head in. It's to do with global
        > variables in Firefox 1.
        >[/color]

        No, it's what Lee said.

        Manipulating strings is a lot faster than date objects. Have a
        look at the code below, it generates dates for any month given a
        year and month. It times methods using date objects and plain
        string methods. On my ancient laptop, the date object method
        consistently took 60 to 70ms, the string method took around 10ms.

        I got the idea to try this from Dr. J's site where he compares
        methods of validating user-entered date strings:

        <URL:http://www.merlyn.demo n.co.uk/js-date4.htm#TDVal >

        Whilst the code is somewhat longer, the overall effect is a
        3-fold increase in speed.


        <script type="text/javascript">
        function createCal0(sMon th){

        var o = document.getEle mentById('write Span');
        var m = sMonth.split(/\D+/);
        m[1]--; // Adjust month number
        var dateObj = new Date(m[0],m[1]);
        var t; // Only used 'cos appendChild line was too long

        while (m[1] == dateObj.getMont h()){
        t = addZ(dateObj.ge tDate());
        o.appendChild(d ocument.createT extNode(t + ','));
        dateObj.setDate (dateObj.getDat e()+1)
        }
        }

        function createCal1(sMon th){
        var o = document.getEle mentById('write Span');
        var m = sMonth.split(/\D+/);
        var limit;
        var ds = [];
        if ( m[1]==4 || m[1]==6 || m[1]==9 || m[1]==10) {
        limit = 30;
        } else if (m[1]==1 || m[1]==3 || m[1]==5
        || m[1]==7 || m[1]==8 || m[1]==10 || m[1]==12){
        limit = 31;
        } else {
        limit = 28;
        if ( m[0]%4 == 0 ) limit = 29;
        if ( m[0]%100 == 0 ) limit = 28;
        if ( m[0]%400 == 0 ) limit = 29;
        }
        for (var i=1; i<=limit; i++) {
        ds.push(addZ(i) );
        }
        o.innerHTML = ds.join(',');
        }

        function addZ(x){
        return (x<10)?'0'+x:x;
        }
        </script>
        <form>
        <input name="ym" value="2005-02">Enter a year
        and month (yyyy-mm)<br>
        <button onclick="
        var s = new Date();
        createCal0(this .form.ym.value) ;
        var f = new Date();
        var t = f - s;
        alert('That took ' + t + ' ms');
        return false;
        ">write dates 0</button>
        <br>
        <button onclick="
        var s = new Date();
        createCal1(this .form.ym.value) ;
        var f = new Date()
        var t = f - s;
        alert('That took ' + t + ' ms');
        return false;
        ">write dates 1</button>
        <br>
        </form>
        <span id="writeSpan"> </span>


        --
        Rob

        Comment

        • Lee

          #5
          Re: firefox global variables woes

          barabis said:[color=blue]
          >
          >It's funny that it doesnt affect IE. No wonder a lot of the dhtml calendars
          >don't work in firefox tho.[/color]

          Yes. There is a lot of bad code out there.

          Comment

          • Dr John Stockton

            #6
            Re: firefox global variables woes

            JRS: In article <420a2052$0$102 00$5a62ac22@per-qv1-newsreader-
            01.iinet.net.au >, dated Thu, 10 Feb 2005 00:33:22, seen in
            news:comp.lang. javascript, RobG <rgqld@iinet.ne t.auau> posted :[color=blue]
            >
            >function createCal1(sMon th){
            > var o = document.getEle mentById('write Span');
            > var m = sMonth.split(/\D+/);
            > var limit;
            > var ds = [];
            > if ( m[1]==4 || m[1]==6 || m[1]==9 || m[1]==10) {
            > limit = 30;
            > } else if (m[1]==1 || m[1]==3 || m[1]==5
            > || m[1]==7 || m[1]==8 || m[1]==10 || m[1]==12){
            > limit = 31;
            > } else {
            > limit = 28;
            > if ( m[0]%4 == 0 ) limit = 29;
            > if ( m[0]%100 == 0 ) limit = 28;
            > if ( m[0]%400 == 0 ) limit = 29;
            > }
            > for (var i=1; i<=limit; i++) {
            > ds.push(addZ(i) );
            > }
            > o.innerHTML = ds.join(',');
            >}[/color]


            Probably quicker to declare var limit=31 and then overwrite it if
            (Apr Jun Sep Nov) / Feb ; avoids 7 tests.

            You have half-transferred a day from Oct to Nov - that is an Emperor-of-
            Rome grade decision!

            I'd try changing to M = m[1] ; ... if (M==4 || M==6 || ... to reduce
            indexing.

            To avoid all that pushing and joining, you could try a substring
            operation on "01,02,03,0 4, ... ,31". Or start ds="01,02, ... ,28" .

            Your Leap Year test tries all three divisors every time, which is
            readily avoidable.

            The month lengths can be computed, except for Feb, by adapting Zeller's
            Congruence <URL:http://www.merlyn.demo n.co.uk/zeller-c.htm>; or, for
            Martin Honnen &c., <URL:http://www.merlyn.demo n.co.uk/zel-86px.htm>.

            Or global var ML = [31,0,31,30, ...,31]
            and limit = ML[m[1]] ; if (!limit) limit = <28 or 29>.

            --
            © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
            Web <URL:http://www.merlyn.demo n.co.uk/> - w. FAQish topics, links, acronyms
            PAS EXE etc : <URL:http://www.merlyn.demo n.co.uk/programs/> - see 00index.htm
            Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.

            Comment

            • RobG

              #7
              Re: firefox global variables woes

              Dr John Stockton wrote:[color=blue]
              > JRS: In article <420a2052$0$102 00$5a62ac22@per-qv1-newsreader-
              > 01.iinet.net.au >, dated Thu, 10 Feb 2005 00:33:22, seen in
              > news:comp.lang. javascript, RobG <rgqld@iinet.ne t.auau> posted :
              >[color=green]
              >>function createCal1(sMon th){
              >> var o = document.getEle mentById('write Span');
              >> var m = sMonth.split(/\D+/);
              >> var limit;
              >> var ds = [];
              >> if ( m[1]==4 || m[1]==6 || m[1]==9 || m[1]==10) {
              >> limit = 30;
              >> } else if (m[1]==1 || m[1]==3 || m[1]==5
              >> || m[1]==7 || m[1]==8 || m[1]==10 || m[1]==12){
              >> limit = 31;
              >> } else {
              >> limit = 28;
              >> if ( m[0]%4 == 0 ) limit = 29;
              >> if ( m[0]%100 == 0 ) limit = 28;
              >> if ( m[0]%400 == 0 ) limit = 29;
              >> }
              >> for (var i=1; i<=limit; i++) {
              >> ds.push(addZ(i) );
              >> }
              >> o.innerHTML = ds.join(',');
              >>}[/color]
              >
              >
              >
              > Probably quicker to declare var limit=31 and then overwrite it if
              > (Apr Jun Sep Nov) / Feb ; avoids 7 tests.
              >
              > You have half-transferred a day from Oct to Nov - that is an Emperor-of-
              > Rome grade decision!
              >
              > I'd try changing to M = m[1] ; ... if (M==4 || M==6 || ... to reduce
              > indexing.
              >
              > To avoid all that pushing and joining, you could try a substring
              > operation on "01,02,03,0 4, ... ,31". Or start ds="01,02, ... ,28" .
              >
              > Your Leap Year test tries all three divisors every time, which is
              > readily avoidable.
              >
              > The month lengths can be computed, except for Feb, by adapting Zeller's
              > Congruence <URL:http://www.merlyn.demo n.co.uk/zeller-c.htm>; or, for
              > Martin Honnen &c., <URL:http://www.merlyn.demo n.co.uk/zel-86px.htm>.
              >
              > Or global var ML = [31,0,31,30, ...,31]
              > and limit = ML[m[1]] ; if (!limit) limit = <28 or 29>.
              >[/color]

              Great, thanks for the tips.

              Given that Zeller's Congruence twisted my brain somewhat and
              code should be maintainable (I'm not sure anyone reading that
              stuff as code would understand it) and that the following
              consistently ran in less than 15ms on page load and 0ms after
              that, further optimisation is gilding the lilly.

              I've used push to "top up" the days of the month rather than
              create separate arrays for 28, 29, 30 & 31 day months.

              It's noted however that Zeller's stuff for day-of-week looks
              pretty handy.

              function createCal1(sMon th){
              var o = document.getEle mentById('write Span');
              var m = sMonth.split(/\D+/);
              var Y = m[0];
              var M = m[1];
              var limit = 31;
              var MD = [1,2,3,4,5,6,7,8 ,9,10,11,12,13, 14,15,16,17,
              18,19,20,21,22, 23,24,25,26,27, 28];

              if ( M==4 || M==6 || M==9 || M==10) {
              MD.push(29,30);
              } else if (M == 2){
              if ((Y%4==0 && Y%100!=0) || (Y%4==0 && Y%400==0)) {
              MD.push(29);
              }
              } else {
              MD.push(29,30,3 1);
              }
              o.innerHTML = MD.join(' ');
              }




              --
              Rob

              Comment

              • Dr John Stockton

                #8
                Re: firefox global variables woes

                JRS: In article <ZADOd.487$Ud4. 38258@news.optu s.net.au>, dated Thu, 10
                Feb 2005 06:56:57, seen in news:comp.lang. javascript, RobG
                <rgqld@iinet.ne t.auau> posted :[color=blue]
                >Dr John Stockton wrote:[/color]
                [color=blue][color=green]
                >> The month lengths can be computed, except for Feb, by adapting Zeller's
                >> Congruence <URL:http://www.merlyn.demo n.co.uk/zeller-c.htm>; or, for
                >> Martin Honnen &c., <URL:http://www.merlyn.demo n.co.uk/zel-86px.htm>.[/color][/color]
                [color=blue]
                > Given that Zeller's Congruence twisted my brain somewhat and
                > code should be maintainable (I'm not sure anyone reading that
                > stuff as code would understand it) and that the following
                > consistently ran in less than 15ms on page load and 0ms after
                > that, further optimisation is gilding the lilly.[/color]

                But the exercise helps develop skills.
                [color=blue]
                > I've used push to "top up" the days of the month rather than
                > create separate arrays for 28, 29, 30 & 31 day months.
                >
                > It's noted however that Zeller's stuff for day-of-week looks
                > pretty handy.[/color]

                I have empirically found the following way of calculating the lengths of
                the months, except February; January must be entered as 13 :-

                function GMLen() { var A = [], m
                for (m=3; m<14; m++) A[m] = 30 + ((3*m+1)%5 < 3)
                document.write( A) }

                ,,,31,30,31,30, 31,31,30,31,30, 31,31

                Can it be improved?

                It's worth remembering that wherever one has a sequence of integers that
                maintains a non-integer average, something Zellerish can compute the
                integers and/or their sum; and, the regrettable Augustan intervention
                notwithstanding , the month-lengths Mar..Jan more or less do so.


                [color=blue]
                > else if (M == 2){
                > if ((Y%4==0 && Y%100!=0) || (Y%4==0 && Y%400==0)) {
                > MD.push(29);
                > }
                > }[/color]


                else if (M == 2 && Y%4==0) {
                if (Y%100!=0 || Y%400==0) {
                MD.push(29);
                }
                } // <G>

                --
                © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
                Web <URL:http://www.merlyn.demo n.co.uk/> - w. FAQish topics, links, acronyms
                PAS EXE etc : <URL:http://www.merlyn.demo n.co.uk/programs/> - see 00index.htm
                Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.

                Comment

                • rh

                  #9
                  Re: firefox global variables woes

                  Dr John Stockton wrote:[color=blue]
                  > JRS: In article <ZADOd.487$Ud4. 38258@news.optu s.net.au>, dated Thu,[/color]
                  10[color=blue]
                  > Feb 2005 06:56:57, seen in news:comp.lang. javascript, RobG
                  > <rgqld@iinet.ne t.auau> posted :[color=green]
                  > >Dr John Stockton wrote:[/color][/color]

                  <...>
                  [color=blue]
                  > I have empirically found the following way of calculating the lengths[/color]
                  of[color=blue]
                  > the months, except February; January must be entered as 13 :-
                  >
                  > function GMLen() { var A = [], m
                  > for (m=3; m<14; m++) A[m] = 30 + ((3*m+1)%5 < 3)
                  > document.write( A) }
                  >
                  > ,,,31,30,31,30, 31,31,30,31,30, 31,31
                  >
                  > Can it be improved?
                  >[/color]

                  Excluding February:

                  function GMLen2() { var A = [], m
                  for (var m=1; m<13; m++) A[m] = 30 | (m>>3^m);
                  document.write( "<P>"+A) }

                  (with improvement by Richard Cornford).

                  Including February:

                  function GMLen3() { var A = [], m, y=2005
                  for (var m=1; m<13; m++) A[m] = 29 + (m>>3^m&1)
                  + (m != 2 || -(y&3 || y&15 && !(y%25)));
                  document.write( "<P>"+A) }

                  Leap year calculation courtesy of JRS/Gabor in this group.

                  Regards,

                  .../rh

                  Comment

                  • Mick White

                    #10
                    Re: firefox global variables woes

                    rh wrote:

                    [snip][color=blue]
                    >
                    > Including February:
                    >
                    > function GMLen3() { var A = [], m, y=2005
                    > for (var m=1; m<13; m++) A[m] = 29 + (m>>3^m&1)
                    > + (m != 2 || -(y&3 || y&15 && !(y%25)));
                    > document.write( "<P>"+A) }
                    >
                    > Leap year calculation courtesy of JRS/Gabor in this group.
                    >[/color]


                    Why not hard code it?
                    function GMLen(m,yyyy){//m 0-11
                    return [31,yy%4==0?new
                    Date(yyyy,m+1,0 ).getDate():28, 31,30,31,30,31, 31,30,31,30,31][m]
                    }

                    Mick

                    Comment

                    • rh

                      #11
                      Re: firefox global variables woes

                      Mick White wrote:[color=blue]
                      > rh wrote:
                      >
                      > [snip][color=green]
                      > >
                      > > Including February:
                      > >
                      > > function GMLen3() { var A = [], m, y=2005
                      > > for (var m=1; m<13; m++) A[m] = 29 + (m>>3^m&1)
                      > > + (m != 2 || -(y&3 || y&15 &&[/color][/color]
                      !(y%25)));[color=blue][color=green]
                      > > document.write( "<P>"+A) }
                      > >
                      > > Leap year calculation courtesy of JRS/Gabor in this group.
                      > >[/color]
                      >
                      >
                      > Why not hard code it?
                      > function GMLen(m,yyyy){//m 0-11
                      > return [31,yy%4==0?new
                      > Date(yyyy,m+1,0 ).getDate():28, 31,30,31,30,31, 31,30,31,30,31][m]
                      > }
                      >[/color]

                      First of all, what you've presented doesn't fit my definition of "hard
                      code". Secondly, it wouldn't appear to have been tested. And thirdly,
                      it doesn't account for leap years properly.

                      Implementation approaches are usually chosen based on taking into
                      account correctness, simplicity and efficiency. Often trade-offs in the
                      latter two are weighed in making a decision.

                      This is a case where efficiency happened to be predominant in the
                      choice, particularly given the context in which the response was made.

                      Moreover, it was coded to parallel the example given by JRS. Obviously
                      it would be structured differently if the intent was to produce a date
                      utilility.

                      Regards,

                      ../rh

                      Comment

                      • Mick White

                        #12
                        Re: firefox global variables woes

                        rh wrote:
                        [color=blue]
                        > Mick White wrote:
                        >[color=green]
                        >>rh wrote:
                        >>
                        >>[snip]
                        >>[color=darkred]
                        >>>Including February:
                        >>>
                        >>> function GMLen3() { var A = [], m, y=2005
                        >>> for (var m=1; m<13; m++) A[m] = 29 + (m>>3^m&1)
                        >>> + (m != 2 || -(y&3 || y&15 &&[/color][/color]
                        >
                        > !(y%25)));
                        >[color=green][color=darkred]
                        >>> document.write( "<P>"+A) }
                        >>>
                        >>>Leap year calculation courtesy of JRS/Gabor in this group.
                        >>>[/color]
                        >>
                        >>
                        >>Why not hard code it?
                        >>function GMLen(m,yyyy){//m 0-11
                        >>return [31,yy%4==0?new
                        >>Date(yyyy,m+1 ,0).getDate():2 8,31,30,31,30,3 1,31,30,31,30,3 1][m]
                        >>}
                        >>[/color]
                        >
                        >
                        > First of all, what you've presented doesn't fit my definition of "hard
                        > code". Secondly, it wouldn't appear to have been tested. And thirdly,
                        > it doesn't account for leap years properly.[/color]

                        oops, typo:
                        function GMLen(m,yyyy){//m 0-11
                        return [31,yyyy%4==0?ne w
                        Date(yyyy,m+1,0 ).getDate():28, 31,30,31,30,31, 31,30,31,30,31][m]
                        }
                        [color=blue]
                        >
                        > Implementation approaches are usually chosen based on taking into
                        > account correctness, simplicity and efficiency. Often trade-offs in the
                        > latter two are weighed in making a decision.
                        >
                        > This is a case where efficiency happened to be predominant in the
                        > choice, particularly given the context in which the response was made.
                        >
                        > Moreover, it was coded to parallel the example given by JRS. Obviously
                        > it would be structured differently if the intent was to produce a date
                        > utilility.
                        >[/color]

                        You're right, but you come off sounding a little pompous. My point is
                        that we need only to calculate February length since it is the only
                        month whose length varies, in that sense 11/12 may be hard coded.
                        Semantics.
                        Mick



                        Comment

                        • rh

                          #13
                          Re: firefox global variables woes

                          Mick White wrote:[color=blue]
                          > rh wrote:
                          >[color=green]
                          > > Mick White wrote:[/color][/color]

                          <...>[color=blue]
                          >
                          > You're right, but you come off sounding a little pompous. My point is[/color]
                          [color=blue]
                          > that we need only to calculate February length since it is the only
                          > month whose length varies, in that sense 11/12 may be hard coded.
                          > Semantics.[/color]

                          Quite right, a more patient response would have been appropriate -- you
                          have my apology.

                          Regards,

                          ../rh

                          Comment

                          • Mick White

                            #14
                            Re: firefox global variables woes

                            rh wrote:
                            [snip]
                            need only to calculate February length since it is the only[color=blue][color=green]
                            >>month whose length varies, in that sense 11/12 may be hard coded.
                            >>Semantics.[/color]
                            >
                            >
                            > Quite right, a more patient response would have been appropriate -- you
                            > have my apology.[/color]

                            No problem
                            y=2004
                            feblen=[28,29][+(new Date(y,1,29).ge tMonth()==1)]

                            Inspiration from Dr. JS (How appropriate)
                            Mick

                            Comment

                            • rh

                              #15
                              Re: firefox global variables woes

                              Mick White wrote:[color=blue]
                              > rh wrote:
                              > [snip]
                              > need only to calculate February length since it is the only[color=green][color=darkred]
                              > >>month whose length varies, in that sense 11/12 may be hard coded.
                              > >>Semantics.[/color]
                              > >
                              > >
                              > > Quite right, a more patient response would have been appropriate --[/color][/color]
                              you[color=blue][color=green]
                              > > have my apology.[/color]
                              >
                              > No problem
                              > y=2004
                              > feblen=[28,29][+(new Date(y,1,29).ge tMonth()==1)]
                              >[/color]

                              <...>

                              Which is a fine example of how to get the most out of the built-in Date
                              function, but doesn't really pertain the earlier question posed by JRS
                              in this thread. Nor, necessarily did my response, as he may have been
                              looking for the possibility an algorithmic improvement, or a range
                              improvement, or both, to the example he provided.

                              Nonetheless, here's yet another predominantly bitwise-operation/logic
                              approach for m = 0..11, February included:

                              daysInMo = 28 | ( m^1 && ++m>>3^m|2 || !(y&3 || y&15 && !(y%25)) );

                              ../rh

                              Comment

                              Working...