'Starting Timer after Cleared in Javascript
I have this code, and I can't figure out how to starting the timer that's cleared at scrollTop, when is scrolledDown, I tried to use
$("#chat").scroll(function(){
var tim = setInterval(function(){
refreshChat();
},4000);
but didn't work, there are a way to fix it? This is my full working code that cleared the timeout at scrollTop:
var tim = setInterval(function(){
refreshChat();
},5000);
$("#chat").scrollTop(function(){
clearTimeout(tim);
});
Solution 1:[1]
You can't restart an interval timer; once it's cleared, it's cleared. You'd have to start a new interval timer.
So
var refreshTimer = 0; // 0 is an invalid handle, useful initial value
function startRefreshTimer() {
if (!refreshTimer) {
refreshTimer = setInterval(refreshChat, 4000);
}
}
function stopRefreshTimer() {
clearInterval(refreshTimer);
refreshTimer = 0;
}
Anywhere you need to stop it, call stopRefreshTimer. Anywhere you need to start it, call startRefreshTimer.
I didn't show clearing the timer the way you did (in a function passed to scrollTop) because scrollTop doesn't support passing a function into it (and if it did, it would probably be like val and text and such where it's used to set a value, not respond to an event).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | T.J. Crowder |
