0

Maybe it's a stupid question but how can I determine the millisecond to delay the calling of a method ? For example if I have multiple delayed calls:

var par=100;
var millisecondsToDelay=40;
    for (i=0;i<par;i++){
        window.setTimeout(function() {
                  myfunction();
                }, millisecondsToDelay);
    }

And the function "myfunction" takes the average of 0.5 seconds to be executed. How can I determine which is the best millisecond to delay? there is a logic I can take into account or it's just something I have to test? Thank you in advance.

navy1978
  • 1,411
  • 1
  • 15
  • 35
  • 3
    Javascript timers aren't very accurate, but if the function is async, which is the only reason the timer would be out of sync, otherwise the UI would be locked etc, add a callback or return a promise – adeneo Jun 19 '16 at 22:23
  • @adeneo thank you for your reply. I'm using node.js and myfunction is parsing a xml file using the xpath module, I don't think it's async, does it mean that if "myfunction" is not async there is no sense to use a timer? And more in general if "myFunction" is async what do you take into account to select the milliseconds to delay the call why I have to use 40 or 100 or 1000? – navy1978 Jun 19 '16 at 22:27
  • Possible duplicate of [Sleep in Javascript - delay between actions](http://stackoverflow.com/questions/758688/sleep-in-javascript-delay-between-actions) – evolutionxbox Jun 19 '16 at 22:30
  • If the function is not async, the calls will be executed after each other anyway. If the function is async, you probably have some kind of callback and can use this. As far as I understand, you don't need a timeout in this case. – Moritz Jun 19 '16 at 22:31
  • @evolutionxbox I read the question you have marked as possible duplicate but I don't think is a duplicate, I just want to know in general how do you determine the milliseconds to wait when you use the timers. In my example I have used 40, but what changes if I use 100 or 1000 in performance speaking... – navy1978 Jun 19 '16 at 22:33
  • Parsing XML is probably synchronous, and you shouldn't need any timeouts for that, each function will complete before you call the next etc? – adeneo Jun 19 '16 at 22:51
  • @adeneo ok I Gert it . But let's assume that in my example myfunction is async. And it takes an average of 0.5 sec to be executed. And you need to update the Dom , so you want to delay these calls, there is a logic to take into account to choose the delay to apply? – navy1978 Jun 19 '16 at 23:14
  • @RobG you are right is not related with jquery , I will remove the tag – navy1978 Jun 19 '16 at 23:14
  • @navy1978—if the async operation has any network dependency, then you can only guess. You might try polling, but that is a last resort. – RobG Jun 19 '16 at 23:45
  • @RobG Ok Thanks... So there is no best practices for that. In any case I'm trying to understand how the workers operate... ;) – navy1978 Jun 20 '16 at 08:13

0 Answers0