Javascript polling server. Will this lead to a stack overflow?

I do not know much about the specifics of each javascript implementation in each browser. However, I know that when using setTimeout, the method passed in the call is called in a separate thread. So using the resulting setTimeout method inside the method will cause its stack to grow indefinitely until it causes a stack overflow? Or will he create a separate column and destroy the current frame when it goes out of focus? Here is the code I'm curious about.

function pollServer()
{
    $.getJSON("poll.php", {}, function(data){
        window.setTimeout(pollServer, 1000);
    });
}

window.setTimeout(pollServer, 0);

I want to poll the server every second or so, but I don’t want to spend CPU cycles on the “lock cycle” - I also don’t want to set timelimit on how long the user can access the page or before their browser dies.

EDIT

Using firebug, I set some breakpoints and looked at the "Script → Stack" panel, that the call stack is literally just "pollServer" and it does not grow per call. This is good - however, do other JS implementations do differently?

+3
source share
4 answers

I am not sure if this will create a stack overflow, but I suggest you use setIntervalif the period is constant.

This is how prototype implements its own PeriodicalExecuter.

// Taken from Prototype (www.prototypejs.org)
var PeriodicalExecuter = Class.create({
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  execute: function() {
    this.callback(this);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.execute();
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
});
+2
source

setTimeout is executed after some time in the future in the event pump circuit. Functions passed to setTimeout are not extensions.

, , .

  • , ?
  • , - ?
  • - ?
  • setTimeout ?

, , answerr .

+1

setTimeout callstack, . , , , .

0

jQuery "SmartUpdater".

http://plugins.jquery.com/project/smartupdater

:

  • stop() - .
  • restart() - minTimeout.
  • continue() - .
  • - ( | | undefined)
  • , .
  • , .
  • ajax, "maxFailedRequests".
0

Source: https://habr.com/ru/post/1713085/


All Articles