1

I have a few large forms that are causing problems with filling them out before the session times out. I need a little javascript to include at the end of the page to ping a file every few minutes to refresh the session timeout for as long as the page is open. So I have a function that the last statement is to call the function again after a gap. Also, for a range of reasons jQuery and other frameworks are not available for this. So I have put this together from https://stackoverflow.com/a/35970894/385011

var getJSON = function(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("get", url, true);
    xhr.responseType = "json";
    xhr.onload = function() {
        var status = xhr.status;
        if (status == 200) {
            callback(null, xhr.response);
        } else {
            callback(status);
        }
    };
    xhr.send();
};

//hearbeat 
function heartbeat(heartbeaturl){
    getJSON(heartbeaturl,function(err, data) {
        console.log(Date.now());
        console.log(data.time);
        setTimeout(heartbeat(heartbeaturl), data.time);
    });
}

console.log("run heartbeat");
heartbeat("heartbeat.json")

data.time is returning 60000 so it should run heartbeat every minute but it sin running every 1~4ms. What am I missing?

Community
  • 1
  • 1
Tyson of the Northwest
  • 2,086
  • 2
  • 21
  • 34

2 Answers2

2

Thats the "setTimeout problem". People forget about what setTimeout does:

function setTimeout(func){
//wait
func();
}

So you need to pass a function to set Timeout. What you actually do is: you pass the result of the function : What you do:

setTimeout(func(parameter),1000);

What you want to do:

setTimeout(func,1000);

But how to pass the parameter? Thats easy:

setTimeout(function(){func(parameter)},1000);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1
setTimeout(heartbeat(heartbeaturl), data.time);

Should be something as:

setTimeout(function () {
    heartbeat(heartbeaturl);
}, data.time)

As otherwise heartbeat(heartbeaturl) is executed immediately without waiting for data.time to be reached.

gor181
  • 1,988
  • 1
  • 14
  • 12
  • 1
    Akternative to creating a new anonymous function is to pass the parameters the to `setTimeout` like so - `setTimeout(heartbeat, data.time, heartbeaturl)`. Anything after the delay will be passed onto the delayed function when it gets executed. – VLAZ Sep 02 '16 at 21:47