最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Trying to call a function every 3 minutes using JavaScript - Stack Overflow

programmeradmin2浏览0评论

I have a function that returns an integer (the current reputation score for a user on a munity site). That number is often going up or down based on how their ments and submissions are voted on. I'd like to "poll" it every 30 seconds or so to see if it's changed, and if so, update the number that I'm displaying.

In another StackOverflow thread, I found this JavaScript snippet that looked useful:

function listen() {
  $.get("/mylongrequestfile", {}, function(data) {
     $("#mydiv").html(data);
     listen(); // then launch again
  }));
};

Do I just replace /mylongrequestfile with my function? I'm trying that but it's not working so well. How do I use this code, or some other snippet, to grab and display this value every 30 seconds?

I have a function that returns an integer (the current reputation score for a user on a munity site). That number is often going up or down based on how their ments and submissions are voted on. I'd like to "poll" it every 30 seconds or so to see if it's changed, and if so, update the number that I'm displaying.

In another StackOverflow thread, I found this JavaScript snippet that looked useful:

function listen() {
  $.get("/mylongrequestfile", {}, function(data) {
     $("#mydiv").html(data);
     listen(); // then launch again
  }));
};

Do I just replace /mylongrequestfile with my function? I'm trying that but it's not working so well. How do I use this code, or some other snippet, to grab and display this value every 30 seconds?

Share Improve this question edited Jul 30, 2013 at 14:21 Gagravarr 48.4k11 gold badges114 silver badges157 bronze badges asked Sep 29, 2009 at 10:28 bflora2bflora2 7533 gold badges8 silver badges27 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You can use

window.setInterval

which

Calls a function repeatedly, with a fixed time delay between each call to that function.

var intervalID = window.setInterval(yourfunctionname, 300);

This executes in a delay of 300 milliseconds.

Callback arguments

setInterval() will pass the number of milliseconds late the callback was called into the callback function, which can confuse it if it expects something else as an argument. To sidestep that problem, use an anonymous function to call your callback.

The same technique can be used if you need to pass an argument to your callback function, but need it to work in Internet Explorer, which doesn't support sending additional parameters with setInterval().

var intervalID = setInterval(function() { YourFunction(); }, 300);
var listener = function () {
$.get("http://www.domain.tld/script/", {}, function(data) {
    $("#mydiv").html(data);
}));
};

var interval = setInterval(listener, 30000);
发布评论

评论列表(0)

  1. 暂无评论