如何在Javascript / jQuery中重置超时? [英] How to reset timeout in Javascript/jQuery?

查看:111
本文介绍了如何在Javascript / jQuery中重置超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网页中有一个字段A,当用户编辑时,调用API调用(使用jQuery),更新字段B.编辑后,应每隔10秒调用一次API来更新B场再次出现。我目前使用:

I've got a field A in my webpage which, when edited by the user, invokes an API call (using jQuery), which updates field B. After the edit, the API should be called every 10 seconds to update the field B again. I currently do this using:

setTimeout(thisFunction, 10000);

问题是每次用户编辑字段A时都会设置此超时,在编辑字段A后几次导致超时被设置多次,并且API被多次调用。这使得网站看起来非常紧张。

The problem is that this timeout is set every time the user edits field A, which after editing field A a couple times causes the timeout to be set multiple times and the API to be called many many times. This makes the website look pretty stressy.

我想要做的是,每次编辑字段时都设置一个新的超时,无论是通过用户编辑字段A,或间隔达到10秒,从而轮询API。换一种说法;如果字段B未更新10秒或更长时间,则应更新该字段。

What I would rather like to do, is set a new timeout every time the field is edited, be it either by the user editing field A, or by the interval reaching 10 seconds and thereby polling the API. In other words; the field should be updated if field B wasn't updated for 10 or more seconds.

最后,如果用户然后单击按钮C,则轮询应该停止。

Lastly, if the user then clicks button C, the polling should stop.

所以我的问题;如果该字段B没有更新10秒或更长时间,如何运行一个更新字段B的函数?如何在我想要的时候停止轮询(当用户点击另一个按钮时)欢迎所有提示!

So my question; how can I run a function to update field B if that field B wasn't updated for 10 or more seconds and how do I stop the polling when I want to (when the user clicks another button) All tips are welcome!

推荐答案

可以使用 clearTimeout 取消计时器,所以:

A timer can be cancelled with clearTimeout, so:

var timer = null;
if (timer) {
    clearTimeout(timer); //cancel the previous timer.
    timer = null;
}
timer = setTimeout(thisFunction, 10000);

这篇关于如何在Javascript / jQuery中重置超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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