-1

Following calls a functions every 10 seconds. It does not call the function immediately, just after the first 10 seconds.

window.setInterval(function(){
  /// foo
}, 10000);

How do I call the function first, then call it every x seconds, what would be the best way of doing this?

utdev
  • 3,942
  • 8
  • 40
  • 70

2 Answers2

4

Either give it a name and call it right after the setInterval

function repeat(){
//foo
}

window.setInterval(repeat, 10000);
repeat();

Or use setTimeout instead and call it from inside the function

function repeat(){
 //foo
 setTimeout(repeat, 10000);
}
repeat();
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
0

EDIT:

<html>
    <head><title>Timeout testing</title></head>
    <body onload="callMe()">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <script type="text/javascript">
    function callMe()
    {
        window.console.log('called');
        window.setTimeout(callMe, 1000);
    }
    $(".realContent").click(function() {

         var data = [ {"id":1,"start":"/Date(1401993000000+0530)/"} ];
         var myDate = new Date(data[0].start.match(/\d+/)[0] * 1);
         myDate =  new Date(myDate.getTime() + myDate.getTimezoneOffset() * 60 * 1000);
         alert(myDate);


    })
    </script>
    </body>
    </html>
Tejas Vaishnav
  • 492
  • 2
  • 14
  • 1
    While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – DimaSan Jun 20 '17 at 13:59