• (cs) in reply to JimM
    JimM:
    chubertdev:
    I'm sorry, you think that default names will open the gates to hell?

    Well, I have personal experience of watching client side code break horribly between a test server deployment and a live server deployment due to ASP.NET default naming and unnamed containing controls. Both servers had identical configurations, as far as anyone could tell. Trying to resolve it felt like I'd been at least dragged into Purgatory, if not Hell itself...

    Any time your client side code relies on server-side automagical naming, you're asking for trouble. How hard is it to name the containing control yourself?

    Although frankly, anyone who uses Webforms as is deserves throwing into hell anyway. IMNSHO, of course.

    I've seen developers struggle with that issue many times. Emphasis on "developers struggle."

  • (cs) in reply to JimM
    JimM:
    chubertdev:
    TRWTF is thinking that the data should be held in a control instead of simply displayed there. That was the developer's first mistake.

    I'm sorry: this is written in ASP.NET, using default controls with the default naming convention, as far as we can see it imports an entire js framework to get access to one function ($find), it performs string manipulation to decrement a value, and it uses client side code to attempt to implement a "security" feature - but your biggest issue with it is storing data in a control?!

    tbh, I wouldn't be at all surprised to find that getComputedStyle(document.getElementById('ctl00_lblTimer')) had a display:none; declaration in there somewhere: the existence of "ctl00_lblWaitClock" and "runWaitForClock()" send shivers down my spine.

    Although as already noted, setTimeout() is a very poor substitute for a properly implemented sleep, and I'd be frankly amazed if this code actually worked in any meaningful way...

    Bad terminology. The control does not have a "default name," but rather what you are seeing is a decorated name. You have (virtually) no control over the way ASP.NET will decorate your names, and, that aside, the default name for a label would be Label1, so the coder clearly changed the name to lblWaitClock. Nothing "default" to see here.

  • (cs) in reply to Pawprint
    Pawprint:
    Bad terminology. The control does not have a "default name," but rather what you are seeing is a decorated name. You have (virtually) no control over the way ASP.NET will decorate your names ...

    the lblWaitClock isn't the issue, it's the ctl00_ before it. That's there because there's a server parsed control wrapping the label, that hasn't been named by the developer. If you understand why the "decoration" is there, you have plenty of control over it...

  • Tux "Tuxedo" Penguin (unregistered) in reply to C-Derb
    C-Derb:
    rohcQaH:
    How to spot someone who doesn't understand javascript, without even looking:
    I know it is possible to smoke something without inhaling, but can you also smell something without breathing? Feel something without touching? Hear something without listening? Taste something without eating?

    There's that thing called Synestesia that can help you with that.

  • Tux "Tuxedo" Penguin (unregistered) in reply to Norman Diamond
    Norman Diamond:
    Some Damn Yank:
    faoileag:
    Meep:
    Of course, smart programmers check the actual time after being awakened so as not to allow the difference between requested and actual sleep time to skew things.
    No, they figure out how to properly signal when things are done, and don't use sleep as a crutch.
    So please, post your sleep-less solution to the given problem ("display a ten-minute countdown on a webpage using Javascript; the visible remaining time should be accurate to one second") here in the comments section of TDWTF for our pleasure.
    X = Current_Time; While Current_Time - X < 10minutes; Print 10minutes + X - Current_Time; End;
    In a country with daylight savings time, everyone will get logged out instantaneously.

    Unless Current_Time = local user's time (taken with JS function) and not server time.

    ingenium - material my brain is made of.

  • Tux "Tuxedo" Penguin (unregistered) in reply to faoileag
    faoileag:
    Nobulate:
    Amazingly no one thought to store the time in an integer, as seconds. Variable rate of decrement I can live with (think The Doppler Effect), but string manipulation? Guffah and Inexcusable!
    Unfortunately, if you did that, you would have to transform the epoch time into something legible, e.g. 9:59.

    What is faster (decrementing a string "9:59" or transforming 599 into "9:59") I don't know but you would probably not gain much.

    string fromSeconds(int seconds) {
        return ((int)seconds/60).toString+":"+seconds%60.toString;
    }
  • anonymous (unregistered) in reply to Tux "Tuxedo" Penguin
    Tux "Tuxedo" Penguin:
    faoileag:
    Nobulate:
    Amazingly no one thought to store the time in an integer, as seconds. Variable rate of decrement I can live with (think The Doppler Effect), but string manipulation? Guffah and Inexcusable!
    Unfortunately, if you did that, you would have to transform the epoch time into something legible, e.g. 9:59.

    What is faster (decrementing a string "9:59" or transforming 599 into "9:59") I don't know but you would probably not gain much.

    string fromSeconds(int seconds) {
        return ((int)seconds/60).toString+":"+seconds%60.toString;
    }
    0:0 0:1 0:2 0:3 0:4 0:5 0:6 0:7 0:8 0:9 0:10 0:11 . . . 0:59 1:0 1:1 . . .
  • IdleEric (unregistered)

    I guess this week's WTF is the comments section ...

    "I've never touched Javascript in my life and think that AJAX is a language ... but I'll open my dumb mouth and spout my useless opinion anyway! Here's some entirely irrelevant C psuedo-code!"

    CAPTCHA: augue - I can't believe the augue of these people.

  • FennNaten (unregistered) in reply to faoileag

    Javascript is single threaded and doesn't have the concept of sleep. It's a big neverending event listener waiting for the browser to give it events to process. What's done in the code showed in the article is putting a handler in the browser's js engine queue at the given time. So actually, it is a sleep-less solution. At least part of your requirements is met. The part about accuracy isn't doable. Precisely because js is single-threaded: you have the garantee that the handler will be in the queue at the time you specified, but if one or several previous handlers take more than a second to execute, your time handler execution will be delayed.

    By talking about the sleep command, the article mislead the readers with a wrong analogy.

    That's said, all the commenters saying to others that they don't know js but who haven't been able to spot that can go back to basic js learning.

  • Norman Diamond (unregistered) in reply to Tux "Tuxedo" Penguin
    Tux "Tuxedo" Penguin:
    Norman Diamond:
    Some Damn Yank:
    faoileag:
    Meep:
    Of course, smart programmers check the actual time after being awakened so as not to allow the difference between requested and actual sleep time to skew things.
    No, they figure out how to properly signal when things are done, and don't use sleep as a crutch.
    So please, post your sleep-less solution to the given problem ("display a ten-minute countdown on a webpage using Javascript; the visible remaining time should be accurate to one second") here in the comments section of TDWTF for our pleasure.
    X = Current_Time; While Current_Time - X < 10minutes; Print 10minutes + X - Current_Time; End;
    In a country with daylight savings time, everyone will get logged out instantaneously.
    Unless Current_Time = local user's time (taken with JS function) and not server time.
    Huh?

    User's time: X is assigned. User's clock jumps ahead 1 hour. Current time is 1 hour later than X. User gets logged out.

    Server time: X is assigned. Server's clock jumps ahead 1 hour. Current time is 1 hour later than X. User gets logged out.

  • anonymous (unregistered) in reply to FennNaten
    FennNaten:
    Javascript is single threaded
    No:
    The Worker interface spawns real OS-level threads
  • FennNaten (unregistered) in reply to anonymous
    anonymous:
    FennNaten:
    Javascript is single threaded
    No:
    The Worker interface spawns real OS-level threads

    Ok, I can be more precise if you want, javascript is single-threaded, except if you create a web worker dedicated to a task (fully detached from the window context), which will miserably fail on IE < 10 and android browsers, with no possibility to emulate the behavior. can i use web workers? And that changes nothing about my previous point: the way showed in the article is single threaded and without sleep. (and I don't think web workers support sleep either).

  • Rudolf (unregistered) in reply to FennNaten
    FennNaten:
    The part about accuracy isn't doable. Precisely because js is single-threaded: you have the garantee that the handler will be in the queue at the time you specified, but if one or several previous handlers take more than a second to execute, your time handler execution will be delayed.

    The accuracy is totally doable - there was a clue in the article.

    Do not expect 'setTimeout' to give you accurate times, so rather than 'setTimeout(updateTimer, 1000)', use 'setTimeout(updateTimer, 100)' and use 'new Date().getTime()' to get the time in ms since your timeout period started.

    Then it doesn't matter how much time is actually between the setTimeout events, you can still show the time to within 100ms or so (if you need more accuracy, increase the frequency of the setTimeouts

  • anonymous (unregistered) in reply to FennNaten
    FennNaten:
    And that changes nothing about my previous point: the way showed in the article is single threaded and without sleep. (and I don't think web workers support sleep either).
    No, and I didn't quote the part of your comment with which I had no argument. And no, they don't, which is why I posted this:
    anonymous:
    Javascript doesn't actually have any way to sleep.
    Rudolf:
    Do not expect 'setTimeout' to give you accurate times, so rather than 'setTimeout(updateTimer, 1000)', use 'setTimeout(updateTimer, 100)' and use 'new Date().getTime()' to get the time in ms since your timeout period started.
    Well, you should really use setInterval rather than setTimeout. Either way will work, though.
  • nmclean (unregistered) in reply to FennNaten
    FennNaten:
    The part about accuracy isn't doable. Precisely because js is single-threaded: you have the garantee that the handler will be in the queue at the time you specified, but if one or several previous handlers take more than a second to execute, your time handler execution will be delayed.

    Yes, it is doable. The fact that it uses an event loop instead of threading is unrelated to this. Even in a threaded solution you would need to use the same approach to preserve accuracy.

    It's true that javascript doesn't have the true concept of "sleep", but again this has nothing to do with threads. A true sleep function involves cooperation with the hardware, namely the halt instruction (HLT).

  • Andrew (unregistered) in reply to Meep

    I second this, TRWTF is not knowing what "smart programmers" really do. Use calls that do a callback, interrupt, or some equivalent when time is up. Don't poll!

  • nmclean (unregistered) in reply to Andrew
    Andrew:
    I second this, TRWTF is not knowing what "smart programmers" really do. Use calls that do a callback, interrupt, or some equivalent when time is up. Don't poll!

    What exactly did the article say that "smart programmers" do that was not correct?

    It said they "check the actual time after being awakened so as not to allow the difference between requested and actual sleep time to skew things."

    That is exactly how you should implement a timer display refresh. It has nothing to do with polling.

  • FennNaten (unregistered) in reply to anonymous
    anonymous:
    FennNaten:
    And that changes nothing about my previous point: the way showed in the article is single threaded and without sleep. (and I don't think web workers support sleep either).
    No, and I didn't quote the part of your comment with which I had no argument. And no, they don't, which is why I posted this:
    anonymous:
    Javascript doesn't actually have any way to sleep.
    Rudolf:
    Do not expect 'setTimeout' to give you accurate times, so rather than 'setTimeout(updateTimer, 1000)', use 'setTimeout(updateTimer, 100)' and use 'new Date().getTime()' to get the time in ms since your timeout period started.
    Well, you should really use setInterval rather than setTimeout. Either way will work, though.

    I'm sorry, I've read too quickly and missed the part mentionning the absence of sleep. Of course, checking the actual date before updating your 'clock' is mandatory. And I agree about the fact that using setTimout/setInterval can give you a good level of precision, but this assumes that your 'clock' is the only thing running, or at least no time-consuming task have been put in the queue. (and no long garbage collection occurs) Checking the time will enable you to correct your 'clock' with the right amount of time passed, but you won't be able to garantee that your 'display' will show every passing second, that's what I meant by saying that no real accuracy can be achieved. Again, mpy bad, should have been more precise instead of assuming a context without explaining it. Always documenting your assumption ^^'

  • FennNaten (unregistered) in reply to nmclean
    nmclean:
    FennNaten:
    The part about accuracy isn't doable. Precisely because js is single-threaded: you have the garantee that the handler will be in the queue at the time you specified, but if one or several previous handlers take more than a second to execute, your time handler execution will be delayed.

    Yes, it is doable. The fact that it uses an event loop instead of threading is unrelated to this. Even in a threaded solution you would need to use the same approach to preserve accuracy.

    It's true that javascript doesn't have the true concept of "sleep", but again this has nothing to do with threads. A true sleep function involves cooperation with the hardware, namely the halt instruction (HLT).

    For the part about accuracy, see my previous post. I was initially answering to a post in first page stating:

    "display a ten-minute countdown on a webpage using Javascript; the visible remaining time should be accurate to one second"

    So I both:

    • assumed that each second should be displayed, without miss. That's what I meant by 'accuracy'. Checking the real elapsed time is of course a no-brainer.
    • assumed that the context will be a real page doing other stuff. That's why I said: cannot be guaranteed, due to event loop: a long task stacked before an update can make you miss a second and there's nothing you can do about it.

    For the part about thread and sleep, what I meant is, a language like javascript, being mainly used single-threaded, won't implement it, because the sleep would block everything, and you usually don't want to do that (or to allow that if you're a browser vendor). That is for me the relation between the 'single threaded' and 'no sleep'. It wasn't about a real technical impossibility.

    Sorry again, I'm not a native English speaker, and what's crystal clear in my head appears to be not so clear when written down.

  • anonymous (unregistered) in reply to FennNaten
    FennNaten:
    For the part about accuracy, see my previous post. I was initially answering to a post in first page stating:
    "display a ten-minute countdown on a webpage using Javascript; the visible remaining time should be accurate to one second"

    So I both:

    • assumed that each second should be displayed, without miss. That's what I meant by 'accuracy'. Checking the real elapsed time is of course a no-brainer.

    • assumed that the context will be a real page doing other stuff. That's why I said: cannot be guaranteed, due to event loop: a long task stacked before an update can make you miss a second and there's nothing you can do about it.

    A robust way to create a timer would be something like this:
    function Timer(initial, update, interval, floating) {
    // initial:     starting value of timer, in seconds
    // update:      update() is passed the current time in seconds and the original Timer object
    // interval:    update interval of timer in milliseconds (default is 100 ms)
    // floating:    indicates that update() accepts a non-integer time value (default is false)
    // if floating is true, update() is called at every interval; if not, it's called once per second
    // note that cpu lock will cause this to skip ticks, but the timer will not lose any time

    // the resulting Timer object contains two methods: // poll: returns the exact number of seconds remaining on the timer // reset: changes the amount of time remaining

    // Timer objects can be re-used by calling reset(), but update() and resolution cannot be changed

    if (typeof initial == "undefined") initial = 0; if (typeof update == "undefined") update = function () {}; if (typeof interval == "undefined") interval = 100; else interval = Math.round(interval); if (interval <= 0) throw new RangeError("Interval must be greater than zero");

    if (typeof floating == "undefined") floating = false;

    this.poll = function poll() { return Math.max(start - (new Date() - startDate) / 1000, 0); }; this.reset = function reset(newRemaining) { if (typeof newRemaining == "undefined") newRemaining = 0; if (i) clearInterval(i); if (t) clearTimeout(t);

      start <b>=</b> Number<b>(</b>newRemaining<b>);</b>
      startDate <b>= <span style="color:#000080;"><i>new</i></span></b> Date<b>();
      
      <span style="color:#000080;"><i>if</i></span> (</b>start <b><</b> <span style="color:red;">0</span><b>) <span style="color:#000080;"><i>throw new</i></span></b> RangeError<b>(</b><span style="color:#808080;">"Initial time cannot be less than zero"</span><b>);
      
      <span style="color:#000080;"><i>if</i></span> (</b>start <b>></b> <span style="color:red;">0</span><b>)</b> i <b>=</b> setInterval<b>(</b>runner<b>,</b> interval<b>);
      <span style="color:#000080;"><i>else</i></span></b> i <b>=</b> <span style="color:red;">0</span><b>;
    

    }

    var runner = function () { // calculate elapsed time and deduct from start time to find time remaining remaining = Math.max(start - (new Date() - startDate) / 1000, 0);

      <span style="color:#000080;"><i>if</i></span> (</b>floating<b>) {</b>
          update<b>(</b>remaining<b>,</b> self<b>);
      } <span style="color:#000080;"><i>else</i></span> {
          <span style="color:#000080;"><i>var</i></span></b> newSeconds <b>=</b> Math.ceil<b>(</b>remaining <b>-</b> interval <b>/</b> <span style="color:red;">1000</span><b>);
          <span style="color:#000080;"><i>if</i></span> (</b>oldSeconds <b>!=</b> newSeconds<b>) {
              <span style="color:#000080;"><i>var</i></span></b> delay <b>= (</b>remaining <b>-</b> newSeconds<b>) *</b> <span style="color:red;">1000</span><b>;
              <span style="color:#000080;"><i>if</i></span> (</b>oldSeconds <b>-</b> newSeconds <b>></b> <span style="color:red;">1</span> <b>&&</b> delay <b>></b> interval<b>) {</b>
                  <span style="color:#008000;">// if something else has hogged the cpu, it's possible that the timer
                  // may miss one or more ticks. in that case, run update() immediately
                  // unless the next tick is less than one interval away</span>
                  update<b>(</b>newSeconds<b>,</b> self<b>);
              } <span style="color:#000080;"><i>else</i></span> {</b>
                  t <b>=</b> setTimeout<b>(<span style="color:#000080;"><i>function</i></span> () {</b>
                      t <b>=</b> <span style="color:red;">0</span><b>;</b>
                      update<b>(</b>newSeconds<b>,</b> self<b>);
                  },</b> delay<b>);
              }</b>
              oldSeconds <b>=</b> newSeconds<b>;
          }
      }
      
      <span style="color:#000080;"><i>if</i></span> (</b>remaining <b><=</b> <span style="color:red;">0</span><b>) {</b>
          clearInterval<b>(</b>i<b>);</b>
          i <b>=</b> <span style="color:red;">0</span><b>;
      }
    

    }

    var start = Number(initial); var oldSeconds = Math.ceil(start - interval / 1000); var startDate = new Date(), i, t, self = this;

    update(start, self); if (start > 0) this.reset(start);

    return this; }

    Here's some example code that uses a Timer to count down 10 seconds and log to the web console:
    function updateTime(seconds, T) {
    console.log(seconds + " (" + T.poll() + ")");
    if (seconds == 0) console.log(((new Date()) - d) / 1000 + " seconds elapsed");
    }

    var d = new Date(); var timer = new Timer(10, updateTime);

  • Filmisek (unregistered)

    НОВИНКИ КИНО И СЕРИАЛЫ https://kinohd.rip/

    https://kinohd.rip/inte - Зарубежные https://kinohd.rip/russ - Отечественные https://kinohd.rip/top-filmov-i-serialov.html - ТОП Кино https://kinohd.rip/top-serialov.html">ТОП Сериалов https://kinohd.rip/top-filmov.html - ТОП Фильмов

  • Filmisek (unregistered)

    НОВИНКИ КИНО И СЕРИАЛЫ https://kinohd.rip/

    https://kinohd.rip/inte - Зарубежные https://kinohd.rip/russ - Отечественные https://kinohd.rip/top-filmov-i-serialov.html - ТОП Кино https://kinohd.rip/top-serialov.html">ТОП Сериалов https://kinohd.rip/top-filmov.html - ТОП Фильмов

  • Joysek (unregistered)

    Джойказино https://joycasino-2c9.ru/

Leave a comment on “The Temporal Countdown Timer”

Log In or post as a guest

Replying to comment #:

« Return to Article