Javascript get status from service

I develop a web application that is getting user updates from a web service (that is in another domain) I want to get the updates every 10 seconds.

For calling the service for the first time I dynamically insert a script in the page. The service is JSONP. Then I would like to define a trigger that insert a script from 10 to 10 seconds to get the updates. Is this correct? Can I do that without affecting the user experience on the website? I mean the site performance … it will be great if I could do the call async and when I have the results I will update the status.

Is there any better solution for accessing the remote services. Is there an efficient way of dynamically reusing the same script using a trigger? I am pretty new to Javascript. Can you give me a short sample how can I define a trigger that calls a remote web service? … or if there is a better solution.


The following will dynamically create the script tags, and delete them (and the global it requires) after being finished with a given call.

You could also use CORS to allow requests besides GET ones, though as you may be aware, that is not supported in older browsers.

To avoid race conditions or performance problems during a slow network, you could allow the JSONP callback to recursively call the function, thereby only making a new call if the callback was returned, though with an optional setTimeout call to ensure there is at least a minimum delay.

The following uses Wikipedia’s API to grab a specific page revision and its user.

var JSONP = function(global){
    // (C) WebReflection Essential - Mit Style ( )
    // 202 bytes minified + gzipped via Google Closure Compiler
    function JSONP(uri, callback) {
        function JSONPResponse() {
            try { delete global[src] } catch(e) { global[src] = null }
            callback.apply(this, arguments);
            src = prefix + id++,
            script = document.createElement("script")
        global[src] = JSONPResponse;
        ).src = uri + "=" + src;
        id = 0,
        prefix = "__JSONP__",
        document = global.document,
        documentElement = document.documentElement
    return JSONP;

// Be sure to include the callback parameter at the end

function startAPI (start) {
    start = start || new Date();
    var url = '|user|comment|content&format=json&callback';
    var minimum = 10000;
    function execute (str) {
    JSONP(url, function (obj) {
        for (var pageNo in obj.query.pages) {
            var page = obj.query.pages[pageNo];
            var str = 'The user ' + page.revisions[0]['user'] + ' left the page with this code ' + page.revisions[0]['*'];
            var elapsed = (new Date().getTime()) - start;
            setTimeout(startAPI, (elapsed < minimum) ? (minimum - elapsed) : 0);

Leave a Reply

Your email address will not be published. Required fields are marked *