尝试使用JavaScript每3分钟调用一次函数 [英] Trying to call a function every 3 minutes using JavaScript

查看:154
本文介绍了尝试使用JavaScript每3分钟调用一次函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回整数的函数(社区网站上用户的当前信誉得分)。根据他们的评论和提交的投票方式,这个数字往往会上升或下降。我想每隔30秒左右轮询一下它是否有变化,如果是,请更新我正在显示的数字。

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.

在另一个StackOverflow线程,我发现这个看起来很有用的JavaScript代码片段:

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

我只是用我的函数替换/ mylongrequestfile吗?我正在尝试,但它没有那么好用。如何使用此代码或其他代码片段每30秒抓取并显示此值?

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?

推荐答案

您可以使用

window.setInterval

重复调用函数,每次调用该函数之间有固定的时间延迟。

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

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

这将延迟300毫秒。

回调参数

setInterval()将传递回调被调用到回调函数后的毫秒数,如果它需要其他东西作为论点。为了回避这个问题,使用匿名函数来调用你的回调。

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.

如果你需要将一个参数传递给你的回调函数,可以使用相同的技术,但需要它在Internet Explorer中工作,它不支持使用setInterval()发送其他参数。

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

这篇关于尝试使用JavaScript每3分钟调用一次函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆