Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
175
rated 0 times [  177] [ 2]  / answers: 1 / hits: 37064  / 10 Years ago, tue, march 4, 2014, 12:00:00

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


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.



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.



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



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!


More From » jquery

 Answers
23

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

[#72157] Monday, March 3, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayla

Total Points: 681
Total Questions: 102
Total Answers: 108

Location: Marshall Islands
Member since Tue, Sep 21, 2021
3 Years ago
tayla questions
Fri, Mar 5, 21, 00:00, 3 Years ago
Wed, Oct 28, 20, 00:00, 4 Years ago
Thu, Apr 9, 20, 00:00, 4 Years ago
;