如何在每个特定时间间隔执行javascript代码? [英] How can I execute javascript code every a specific time interval?

查看:186
本文介绍了如何在每个特定时间间隔执行javascript代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用jQuery每2分钟ping一次服务器。我想过一个带有setTimeout函数的开环,但我认为这会粉碎浏览器 - 任何建议?

I want to ping the server every 2 minutes using jQuery. I thought about an open loop with setTimeout function but I think this would crush the browser - any suggestions ?

推荐答案

不要使用setTimeout ()对于这种类型的操作,而是使用setInterval()。

Do not use setTimeout() for this type of action, rather use setInterval().

var intervalId = setInterval(function() {
    /* Do your magic */
}, 2000);

要清除间隔,只需 clearInterval(intervalId),当你想停止ping:ing。

To clear your interval, simply clearInterval(intervalId), when you wish to stop the ping:ing.

这篇关于如何在每个特定时间间隔执行javascript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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