4
DenRand
7y

Could somebody please help me understand why the fucking hell does JS (I am talking about node.js, so backend) use 32bit integers in setTimeout and setInterval? I mean, I understand most of the choices regarding the language (I have chosen programming languages design and principles for my studies) and I am happily using it for almost 4 years. But I came across an occasion that I had to use big numbers in those functions and it took me a lot of time to figure out why the fuck my code was not working as it was supposed to.
If anyone has a good reason please elaborate. In the meantime I'll go punch some shit to calm down.

Comments
  • 3
    Because JS is still and has always been 32bit based and probably will be until 2030+

    Stop looking into the future 😎
  • 3
    npm install bignumber.js
  • 1
  • 0
    @C0D4 JS has support for 64bit integers in node.js, so I don't believe this is the answer... 😋
  • 1
    @shellbug Even with bignumer package the problem would persist, because the problem is that the two functions are not written with big numbers in mind, not the language itself. To solve it, someone may use safe-timers to replace default setTimeout and setInterval, but that is not an elegant solution I believe.
  • 3
    @DenRand the setInter/Timeout functions from my understanding are not very accurate as is, if you use a number as big as a 32bit int(2.147b) that could hold over 25 days of wait time if you're time out is that long perhaps using a different approach that would be a better/more accurate bet? Like maybe shorter intervals that calculate error in timeout and update timeout accordingly.
  • 0
    @hexc using cron jobs is an option, too.
  • 0
    @hexc I can't resist to ask, your suggestion reminds me a lot of something I read (or seen?) a long time ago, but I am interested in how it was actually done, to refresh my mind.

    Do you mean that there would be two processes, one initially getting slept for X amount of time and the second process in intervals resetting that sleep to how much time is left until the set timestamp - correcting it?
  • 2
    @JoshBent no, I was more thinking making the sleep shorter, after the sleep compare the delta to the target time with the current sleep duration, use whatever is lower as the next sleep, once the final sleep is reached calc the next target time and repeat. If you wanted really good accuracy you could reduce the sleep duration every time you hit like 75% mark on your way to target time, so u gain precision by reducing the sleep timestep as you get closer to the target then for really good accuracy you could put a blocking while loop that checks high precision clock and keeps looping until the target is reached, basically when you set a sleep, it only guarantees it will sleep for at least that amount of time, not that it will end perfectly at that time.
  • 0
    @hexc hah, I brainfarted at night, thanks 😊
Add Comment