开发者

How to check the status each 10 seconds with JavaScript?

开发者 https://www.devze.com 2023-03-26 05:30 出处:网络
I have a server (mysite.com/status), which returns number of active tasks (just a single in开发者_StackOverflow社区teger).

I have a server (mysite.com/status), which returns number of active tasks (just a single in开发者_StackOverflow社区teger). How can I check number of active tasks each 10 seconds with JavaScript and show user something like:

Number of remaining tasks: XXX

And, if number of tasks is 0, then I should load another page.


Make a function set a new timeout calling itself.

function checkTasks(){
    // Make AJAX request
    setTimeout(checkTasks, 10000);
}
checkTasks(); // Start task checking


with jQuery for AJAX functions... (untested code)

setInterval(function(){
  $.get('http://example.com/status',function(d){
    // where there is html element with id 'status' to contain message
    $('#status').text('Number of remaining tasks: '+d)
    if(d == 0){
      window.location = '/another/page'
    }
  })
},10000)


I have thought of different approach, without any AJAX. As you just need to show simple plain data, just use <iframe> to show that dynamic data then with simple JS "reload" the frame every 10 seconds.

HTML would be:

Number of remaining tasks: <iframe id="myFrame" src="mysite.com/status"></iframe>

And the JavaScript:

window.onload = function() {
    window.setTimeout(ReloadTime, 10000);
};

function ReloadTime() {
    var oFrame = document.getElementById("myFrame");
    oFrame.src = oFrame.src;
    window.setTimeout(ReloadTime, 10000);
}

Live test case, using time for the same of example.

With some CSS you can make the frame look like part of the text, just set fixed width and height and remove the borders.


 setInterval(function(elem){     // here elem is the element node where you want to display the message
        var status=checkStatus();  // supposing that the function which returns status is called checkStatus
        if(status == 0){
          window.location = '/another/page'
        }
        else {
         elem.innerHTML="Number of remaining tasks:"+status;
        }
    },10000)


Using the javascript library jquery, you can set a repeating infinite loop. That gets the data from a page and then sets the inner html of an element.

http://jsfiddle.net/cY6wX/14/ This code is untested

edit: demonstration updated Also I did not use the jquery selector for setting the value in case you do not want to use jquery.

0

精彩评论

暂无评论...
验证码 换一张
取 消