I have a loop in my JavaScript that is constantly checking the variable EventCounter
, if eventcounter is zero then it proceeds to do an action then increment it ++, And then it proceeds to do nothing, until that variable changes, here is the code:
EventCounter = {{eg.globals.EventCounter}};
for(var i = 0; i < n; ++i) {
r = rects[i];
ctx.strokeRect((r.x*sc)|0,(r.y*sc)|0,(r.width*sc)|0,(r.height*sc)|0);
window.rects = rects[i];
//console.log(EventCounter);
if (EventCounter === 0) {
console.log("event counter is" + EventCounter)
//setTimeout( function () {document.getElementById("sb").click()}, 5000)
EventCounter++
console.log("event counter is now " + EventCounter);
}
}
}
Now the EventCounter global variable gets its value from the webserver (its a python webserver and its a python variable).
But my question is how do I detect that the variable has changed on the webserver? an ajax request right? how would I go about requesting the variable value to detect if it has changed so that loop can run again? (**the server is incompatible with PHP)
Take a look at WebSockets, which allow a server to send a message to a browser whenever it wants to, once a connection is established. You handle the incoming message with a Javascript event handler, thus avoiding the need to poll continuously.
WebSockets are suported by all major browsers, including IE10. You'd have to make sure, of course, that your server application can support WebSockets too.
You could use WebSockets like Mike W suggests.
Also you could write a script on your python server that returns JSON when it's called and then have the variables you want and their values in the JSON file. This will be supported for all browsers instead of just modern ones like WebSockets require.
Here's a jQuery implementation that polls the server script every 1000ms and displays the result. Your typical response time + browser processing time should be significantly less than your polling interval or your requests might back-up.
Javascript:
Server side PHP: For this example, uses a session variable which it increments on every request and returns a JSON string.