0

I made a custom widget to display live data for every minute .

This is my widget code in which i set settimeout function

(function()
{
  var jQuery;
  if (window.jQuery === undefined)
  {
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type", "text/javascript");
    script_tag.setAttribute("src", "https://code.jquery.com/jquery-2.1.4.js");
    if (script_tag.readyState)
    {
      script_tag.onreadystatechange = function()
      { // For old versions of IE
        if (this.readyState == 'complete' || this.readyState == 'loaded')
        {
          scriptLoadHandler();
        }
      };
    }
    else
    {
      script_tag.onload = scriptLoadHandler;
    }
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
  }
  else
  {
    jQuery = window.jQuery;
    worker();
  }

  function scriptLoadHandler()
  {
    jQuery = window.jQuery.noConflict(true);
    worker();
  }

  function worker()
  {
    alert('worker called');
    jQuery.ajax(
    {
      type: 'GET',
      url: 'http://localhost:8080/RESTWEBAPP/rest/live',
      jsonpCallback: 'jsonCallback',
      cache: false,
      dataType: 'jsonp',
      jsonp: false,
      timeout: 7000,
      success: function(data)
      {
       jQuery('.mysite-widget').append(data.price)
      },
      error: function(x, t, m)
      {
        if (t === "timeout")
        {
          alert("got timeout , please try again");
        }
        else
        {

        }
      },
      complete: function()
      {
        setTimeout(worker(), 60000);
      }
    });
  }
})();

And this is how i embeded the above widget inside my HTML page

<!DOCTYPE html>
<html>
<body>
<script src='http://localhost:8080/RESTWEBAPP/widget.js' type='text/javascript'></script>
<div class='mysite-widget'></div>
</body>
</html>

The issue i am facing is worker function is running for every second.

Could you please let me know how can i resolve this

Pawan
  • 31,545
  • 102
  • 256
  • 434
  • I don't think a down vote is warranted. The question shows the attempt, expected and actual behavior. Yes, it was a duplicate, but it's a lot easier to find the dupe if you know what the problem is. http://meta.stackexchange.com/a/62824/178870 – Ruan Mendes Oct 09 '15 at 11:59

2 Answers2

1

You should pass a reference to worker to setTimeout, not call it

setTimeout(worker(), 60000); // calls worker immediately
setTimeout(worker, 60000); // calls worker in 60 seconds
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
0

This line...

setTimeout(worker(), 60000);

Invokes worker immediately, and passes its return value to setTimeout. You want to pass the function itself, not the result of invoking the function:

setTimeout(worker, 60000);
user229044
  • 232,980
  • 40
  • 330
  • 338