Timeout JavaScript function after being clicked - javascript

I have replaced the iframes on my website with AJAX. It's a lot better now and a lot faster. People can click the refresh button to refresh the dynamic areas.
I am using this function for that:
function djrefresh() {
$('#dj_status').load('inc/dj_status_frame.php');
$('#djbanner').load('inc/djbanner.php');
$('#djknopjes').load('inc/dj_knopjes_frame.php');
$('#djzegt').load('inc/dj_zegt_frame.php');
$('#djfooter').load('inc/footer_frame.php');
$('#berichtenbalkframe').load('inc/berichtenbalk_frame.php');
}
Works perfectly fine, but my site needs to load a lot of stuff all at once. I want the user to be able to click it once and get a timeout for 30 seconds.
... or if you have a better idea please tell me. I don't want the user to DDOS my website with my own scripts. Thanks in advance.

Changing your sites arcitcture is probably the best option, but without more information it's difficult to give any recommendations. Anyhow, to limit calls to djrefresh you can use a debounce function. UnderscoreJS includes the function or you can write one yourself.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
This is taken from https://davidwalsh.name/javascript-debounce-function (I've used it quite a bit personally).
This assumes the "refresh button" is a button the page, not the browser refresh.
Edit: If you do have a refresh button on your site, it would be simpler to just disable it for 30 seconds after it has been clicked.

Just create a count of the calls, use a callback on the calls, if the load has finished on all of them then allow the function to continue.
var djrefresh;
//close values to reduce variable name collision
(function(){
var locked = false;
var callcount = 0;
djrefresh = function() {
if( locked ) return;
locked = true;
$('#dj_status').load('inc/dj_status_frame.php',unlock);
$('#djbanner').load('inc/djbanner.php',unlock);
$('#djknopjes').load('inc/dj_knopjes_frame.php',unlock);
$('#djzegt').load('inc/dj_zegt_frame.php',unlock);
$('#djfooter').load('inc/footer_frame.php',unlock);
$('#berichtenbalkframe').load('inc/berichtenbalk_frame.php',unlock);
}
function unlock(){
if( ++callcount == 6 ) locked = false;
}
})()

Related

When writing a debounce, what is the point of clearTimeout?

debounceFunction() {
let timeout = setTimeout(() => {
doSomething();
flag = true;
clearTimeout(timeout);
}, 250);
}
I wrote a debounce function that looks like the above, I called this function for several times when an event is triggered. My question is, does the clearTimeout at the end of the setTimeout makes any sense?
What would be the optimal way to do it?
Thanks in advance :)
Does the clearTimeout at the end of the setTimeout make any sense?
No, there's no point to call clearTimeout from within the setTimeout callback - it's too late there already. You cannot clear anything, the timeout already occurred.
clearTimeout is used when you want to prevent the callback from getting called before that would happen.
What would be the optimal way to do it?
Just omit it.
If you are asking about the optimal way to write debounce, see Can someone explain the "debounce" function in Javascript.
My question is, does the clearTimeout at the end of the setTimeout
makes any sense?
No, clearTimeout is used to clear the previous created timeout, so clearTimeout should be done before setTimeout in order to cancel out previous invocation of setTimeout.
What would be the optimal way to do it?
Have a look David Walsh's post and SO question
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
clearTimeout() prevents the execution of the function that has been set with setTimeout();
In debouncing, a user is made to perform limited actions in a time interval.
So we set that action inside a function within setTimeout and whenever the user tries to perform the same action within the given interval, we call clearTimeout to prevent user from doing it.
So clearTimeout should be called before SetTimeout.

Javascript event execution deferred in a queue

I'm trying to explain my problem to know the better way to solve it. I've searching a bit, but I don't know how to search exactly:
I have an HTML page with three areas: Panel A, Grid B and Grid C.
On grid C, I can do an action on a row (only clicking it) that updates some counters on panel A and Grid B, but they're calculated on database totals.
When I do the row action I update the row immediately and trigger an event listened by Panel A and Grid B which sends both requests against the server to update it's counters.
Every row update is a bit heavy and if the user clicks various rows fast, the javascript execution is locked flooding the server with updates of Panel A and Grid B which could be deferred to execute only one time if on 1 or 2 seconds the event is not triggered.
I would solve the problem on the listenTo callback because it could be another panel that the event action must be performed "immediately".
I imagine something like this (only refresh after 2 seconds of no event listened), but I think that there must be a better way:
var eventTimeout = {}; // one for listener
element.bind('eventName' function() {
if (eventTimeout['eventName']) {
clearTimeout(eventTimeout['eventName']); // I understand that if the timeout has been exhausted no error is thrown
}
eventTimeout['eventName'] =
setTimeout(function() {
eventTimeout['eventName'] = null;
doAction();
}, 2000);
});
I'll go away with that implementation (I haven't tested yet), when I have more time, I'll put it on a JSFiddle to help to understand.
You are on the right track with your code but you may want to use something like lodash-throttle function decorators rather than reinventing the wheel here IMO.
lodash Throttle
Creates a throttled function that only invokes func at most once per every wait milliseconds. The throttled function comes with a cancel method to cancel delayed invocations. Provide an options object to indicate that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls to the throttled function return the result of the last func call.
examples from their own site:
// avoid excessively updating the position while scrolling
jQuery(window).on('scroll', _.throttle(updatePosition, 100));
// invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
'trailing': false
}));
// cancel a trailing throttled call
jQuery(window).on('popstate', throttled.cancel);
Using the previous #bhantol very valuable response, and some other stackoverflow responses (https://stackoverflow.com/a/43638411/803195) I've published a sample code that simulates the behavior I actually want.
Perhaps it was not well defined on initial question, but I need actually use debounce and it must be dynamic, depending on some variables (a checkbox on the following sample) it must be "delayed" or "immediate":
https://codepen.io/mtomas/pen/xYOvBv
var debounced = _.debounce(function() {
display_info($right_panel);
}, 400);
$("#triggerEvent").click(function() {
if (!$("#chk-immediate").is(":checked")) {
debounced();
} else {
display_info($right_panel, true);
}
});
The sample is based on a original sample published on that (interesting) article:
https://css-tricks.com/debouncing-throttling-explained-examples/
-- UPDATE --
Using debounce of lodash implies me to import full lodash (72Kb minimized), so I've implemented a "lite" own debounce using this reference:
https://davidwalsh.name/function-debounce
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
I've updated my codepen test too.

Interval set through content script being cleared by webpage

In my chrome extension, I have a setInterval in the content script which checks for changes in the webpage after every 3 seconds.
setInterval(detectChange, 3000)
function detectChange(){
...
}
This works perfectly well for all websites except one (www.rdio.com). The webpage scripts somehow clears the interval set through the content script.
I thought of putting the setInterval in background script and sending a message to the content script at each interval. But that would require me to track all the tabs in which the content script is running, which does not seem like a good idea.
Please let me know if there is a way around.
Cancelable task schedulers (setTimeout, setInterval, requestAnimationFrame, etc.) are apparently tied to a document. Although the script execution context of a content script is isolated from the page, the document is not.
It seems rather weird that a site clears timers that are not created by the site itself. You could try to debug the issue, and check why the site is clearing the timer at all by overriding the clearTimeout / clearInterval methods.
Here is an example to catch code that clears timers that are not installed by the script itself:
// Run this content script at document_start
var s = document.createElement('script');
s.textContent = '(' + function() {
var clearTimeout = window.clearTimeout;
var setTimeout = window.setTimeout;
var setInterval = window.setInterval;
// NOTE: This list of handles is NEVER cleared, because it is the
// only way to keep track of the complete history of timers.
var handles = [];
window.setTimeout = function() {
var handle = setTimeout.apply(this, arguments);
if (handle) handles.push(handle);
return handle;
};
window.setInterval = function() {
var handle = setInterval.apply(this, arguments);
if (handle) handles.push(handle);
return handle;
};
window.clearTimeout = window.clearInterval = function(handle) {
clearTimeout(handle);
if (handle && handles.indexOf(handle) === -1) {
// Print a stack trace for debugging
console.trace('Cleared non-owned timer!');
// Or trigger a breakpoint so you can follow the call
// stack to identify which caller is responsible for
// clearing unknown timers.
debugger;
}
};
} + ')();';
(document.head || document.documentElement).appendChild(s);
s.remove();
If this shows that the site is buggy, and (for example) clears every even-numbered timer, then you simply call setTimeout twice to resolve the problem.
For example:
Promise.race([
new Promise(function(resolve) {
setTimeout(resolve, 3000);
}),
new Promise(function(resolve) {
setTimeout(resolve, 3000);
});
}).then(function() {
// Any of the timers have fired
});
If all else fails...
If it turns out that the site clears the timers in an unpredictable way, you could try to use other asynchronous methods or events to schedule tasks, and measure the time between invocations. When a certain time has elapsed, simply trigger your callback. For example, using requestAnimationFrame (which is usually called several times per second):
function scheduleTask(callback, timeout) {
timeout = +timeout || 0;
var start = performance.now();
function onDone(timestamp) {
if (timestamp - start >= timeout) callback();
else requestAnimationFrame(onDone);
}
requestAnimationFrame(onDone);
}
// Usage example:
console.time('testScheduler');
scheduleTask(function() {
console.timeEnd('testScheduler');
}, 1000);
Or insert an <iframe> and create timers in the context of the frame.

Prevent and queue action (but only once globally) if previously called within X seconds

I always run into this problem and seem to implement a nasty looking solution.
It seems like a common design pattern to fire an action immediately, but not let that action queue up if clicked rapidly / delay firing if previously called within a timeframe. In my real world example, I have an AJAX call being made, so if I don't prevent repetitive actions the browser queues requests.
How would you implement this differently? What other options are there?
function myFunction() {
console.log("fired");
}
var timeout = null;
$("#foo").click(function() {
// if not previously clicked within 1 second, fire immediately
if (!timeout) {
myFunction();
timeout = setTimeout(function() {
timeout = null;
}, 1000);
} else {
// clicked again within 1s
clearTimeout(timeout); // clear it - we can't have multiple timeouts
timeout = setTimeout(function() {
myFunction();
timeout = null;
}, 1000);
};
});
With your current code, if you repeatedly click "#foo" at an interval slightly less than one second, say every 800ms, on first click it will fire the function immediately (obviously), but then it will fire the function exactly once more one second after the last click. That is, if you click ten times at 800ms intervals the function will fire once immediately and a second time approximately 8 seconds (800ms * 9 + 1000ms) after the first click.
I think you're better off removing the else case altogether, so that on click it will fire the function if it has not been called within the last second, otherwise it will do nothing with no attempt to queue another call up for later. Not only does that seem to me like a more logical way to operate, it halves the size of your function...
On the other hand, since you mentioned Ajax, rather than disabling the function based on a timer you may like to disable the function until the last Ajax request returns, i.e., use a flag similar to your timerid and reset it within an Ajax complete callback (noting that Ajax complete callbacks get called after success or failure of the request).
In the case of an auto-complete or auto-search function, where you want to send an Ajax request as the user types, you might want to remove the if case from your existing code and keep the else case, because for auto-complete you likely want to wait until after the user stops typing before sending the request - for that purpose I'd probably go with a shorter delay though, say 400 or 500ms.
Regarding general structure of the code, if I wanted a function to be fired a maximum of once per second I'd likely put that control into the function itself rather than in a click handler:
var myFunction = function() {
var timerid = null;
return function() {
if (timerid) return;
timerid = setTimeout(function(){ timerid=null; }, 1000);
// actual work of the function to be done here
console.log("myFunction fired");
};
}();
$("#foo").click(function() {
myFunction();
});
The immediately invoked anonymous function that I've added makes it uglier, but it keeps the timerid variable out of the global scope. If you don't like that obviously you could simply declare timerid in the same scope as myFunction() as you currently do.
This answer is getting kind of long, but if you have a lot of different functions that all need some kind of repeat control in them you could implement a single function to handle that part of it:
function limitRepeats(fn, delay) {
var timerid = null;
return function() {
if (timerid) return;
timerid = setTimeout(function(){ timerid = null; }, delay);
fn();
};
}
// myFunction1 can only be called once every 1000ms
var myFunction1 = limitRepeats(function() {
console.log("fired myFunction1()");
}, 1000);
// myFunction2 can only be called once every 3000ms
var myFunction2 = limitRepeats(function() {
console.log("fired myFunction2()");
}, 3000);
$("#foo").click(function() {
myFunction1();
myFunction2();
});

Fire event after scrollling scrollbars or mousewheel with javascript

I would like to know if it is possible to fire an event after the scrolling of a page, when using the scrollbar or mouse-wheel (or with a swipe on a touch device).
Basically, I'd like to detect when the user has stopped scrolling so I can then AJAX-load, rather than loading while scrolling.
It seems that jQuery's .scroll() is firing every time a user scrolls, and it seems clunky to have an event fire all the time. Is there such thing as .onScrollAfter(), synonymous to the .onMouseUp()?
I'd like to know whether this is possible (or if a function already exists) without using a framework, though I would consider one; especially jQuery.
This event does not exist. You can emulate it by using timeouts:
Example (concept code):
(function() {
var timer;
/* Basic "listener" */
function scroll_finish(ev) {
clearTimeout(timer);
timer = setTimeout(scroll_finished, 200, ev);
//200ms. Too small = triggered too fast. Too high = reliable, but slow
}
window.onscroll = scroll_finish; // Or addEventListener, it's just a demo
// Fire "events"
var thingey = [];
function scroll_finished(ev) {
// Function logic
for (var i=0; i<thingey.length; i++) {
thingey[i](ev);
}
}
// Add listener
window.addScrollListener = function(fn) {
if (typeof fn === 'function') {
thingey.push(fn);
} else {
throw TypeError('addScrollListener: First argument must be a function.');
}
}
window.removeScrollListener = function(fn) {
var index = thingey.indexOf(fn);
if (index !== -1) thingey.splice(index, 1);
}
})();
Thought I would add this as an answer even though it's old. The event you are trying to recreate I believe is synonymous to debounce. This is available in underscore.js
debounce_.debounce(function, wait, [immediate])
Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happen after the input has stopped arriving. For example: rendering a preview of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on.
So it will wait after your last execution of the specific event. if you do not want a delay, you can just specify 0. David Walsh has a pretty nice implementation you can include in any project.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
Which you can go ahead adding by doing
var myEfficientFn = debounce(function() {
// All the taxing stuff you do
}, 250);
window.addEventListener('scroll', myEfficientFn);
Description
You can use the nice jQuery plugin Special scroll events for jQuery by James Padoley.
Works really great.
Check out the page and this jsFiddle Demonstration (Just scroll ;))
More Information
Special scroll events for jQuery
jsFiddle Demonstration

Categories