开发者

How to implement client pull javascript

开发者 https://www.devze.com 2023-03-28 11:47 出处:网络
I am working on an application, where I have one page whose partial content need updating in a interval. I am thinking using JavaScript setInterval to do this task, but I have not used this meth开发者

I am working on an application, where I have one page whose partial content need updating in a interval. I am thinking using JavaScript setInterval to do this task, but I have not used this meth开发者_如何学Good before, so how can I start setinterval when that specific page is loaded and stop setinterval before the page unloaded.

by the way, if you know of any better way to do this kind of task, please be kind to share with me. thanks for any help.


Given that you have a function

function myFunction() {
    ...
}

To run it every n milliseconds, use

setInterval(myFunction, n);

You won't need to stop the interval yourself when the page is 'unloaded' or traversed away from; this is done automatically. If, however, you wish to stop it at any other time, then save the return value of setInterval when you use it, like this:

var timer_id = setInterval(myFunction, n);

and use this to stop the interval timer:

clearInterval(timer_id);


This tutorial should help you: How To Check For New Tweets From a User


To start the timer you just call setInterval as the page loads. You don't need to stop the timer as it will stop automatically when the page is unloaded.

Here is an example copied from the w3schools website which also shows how to manually stop the timer if necessary via clearInterval:

http://www.w3schools.com/jsref/met_win_setinterval.asp

<html>
<body>

<input type="text" id="clock" />
<script language=javascript>
var int=self.setInterval("clock()",1000);
function clock()
  {
  var d=new Date();
  var t=d.toLocaleTimeString();
  document.getElementById("clock").value=t;
  }
</script>
</form>
<button onclick="int=window.clearInterval(int)">Stop</button>

</body>
</html>
0

精彩评论

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