Trying to call a function every 3 minutes using JavaScript

自作多情 提交于 2019-12-23 01:37:26

问题


I have a function that returns an integer (the current reputation score for a user on a community site). That number is often going up or down based on how their comments 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?


回答1:


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);



回答2:


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

var interval = setInterval(listener, 30000);


来源:https://stackoverflow.com/questions/1491737/trying-to-call-a-function-every-3-minutes-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!