JavaScript event handling scroll event with a delay - javascript

Can someone explaine and help me with this. My webpage is slugish because the scroll function is dragging it down. I need to add a delay but don't understand how to do this.
$(window).scroll(handleScroll);

You could write a simple throttle debounce function to limit the times per second the scroll event will be handled.
function debounce(method, delay) {
clearTimeout(method._tId);
method._tId= setTimeout(function(){
method();
}, delay);
}
$(window).scroll(function() {
debounce(handleScroll, 100);
});
This will make sure there's at least 100ms between each call to handleScroll (or, in other words, it's called at most 10 times per second).
As zzzzBov pointed out, what Zakas describes as a throttle function is actually a debounce function. The difference is that debounce discards the superfluous scroll events, while a throttle function should queue them up to be handled later (but at a given maximum rate).
In the case of scroll events, you don't want real throttling.

For scroll, you most likely need a throttle function like in Lodash or Underscore; great example:
function throttle(func, timeFrame) {
var lastTime = 0;
return function () {
var now = new Date();
if (now - lastTime >= timeFrame) {
func();
lastTime = now;
}
};
}
This is a simple implementation from this repo
It depends on what you implement by scrolling callback. In some cases, the throttle will be much better to use. For example, infinite scrolling.
So debounce only would trigger only when the user stops scrolling and we need to start fetching the content before the user reaches the bottom.
But with throttle, we can warranty that we are constantly checking how far we are from the bottom.
Conclusion:
debounce: Grouping a sudden burst of events (like keystrokes) into a single one.
throttle: Guaranteeing a constant flow of executions every X milliseconds. Like checking every 200ms of your scroll position to trigger a CSS animation.
requestAnimationFrame: a throttle alternative. When your function recalculates and renders elements on the screen and you want to guarantee smooth changes or animations. Note: no IE9 support.

Related

Is there a better solution than setInterval when I need the interval to be very precise over time?

I'm building a browser game similar to Guitar Hero. The way it works is setInterval is set to execute every 16th note depending on the tempo, which is usually 100-150 milliseconds. The function it executes just checks if there's a note that needs to be checked against the user's keypresses.
But I've been reading about how setInterval can suffer from drift and may not be very accurate. For a song that lasts 3-4 minutes and needs 100ms precision (if the timing mechanics are even slightly off, that might be very frustrating for the users), it seems like it may not be the greatest solution.
So is there an alternative that's more precise? T
It probably would be a better idea to calculate everything in absolute time. So have a var starttime = Date.now();, and then calculate where every note should be var expected_note_time = starttime+beat_interval*beat_number. You can then add a listener on keypress and then log the exact time the keypress was hit. If abs(time_pressed-expected_note_time) < ALLOWED_MISTAKE_VARIANCE, then add that point to the user's score. Good luck.
Agree, setInterval have some issues, like it doesn't care whether the callback is still running or not and isn't that flexible.
you can implement you own method something like this :
function interval(func, wait, times){
var interv = function(w, t){
return function(){
if(typeof t === "undefined" || t-- > 0){
setTimeout(interv, w);
try{
func.call(null);
}
catch(e){
t = 0;
throw e.toString();
}
}
};
}(wait, times);
setTimeout(interv, wait);
};
this function has an internal function called interv which gets invoked automatically via setTimeout, within interv is a closure that checks the the repetition times, invokes the callback and invokes interv again via setTimeout. In case an exception bubbles up from the callback call the interval calling will stop and the exception will be thrown.
you can use it like this :
interval(function(){
// Code block goes here
}, 1000, 10);
which execute a piece of code 5 times with an interval or 10 seconds and you can do something in between.
You could cache the ticks at the start of the song, get the number of ticks since then, see if a note exists at that point.
Return the number of milliseconds since 1970/01/01:
var d = new Date();
var n = d.getTime();
The result of n could be:
1502156888172
From: https://www.w3schools.com/jsref/jsref_gettime.asp
and needs 100ms precision
The setInterval() function will drift because of the way javascript is built (event loop) and if you block it with a heavy CPU intensive task, it will delay. However, the drift will be very small (less that a ms) if you do it correctly.
A good way to avoid that would be to use multiple thread, but that is not easily achieved in JavaScript.

Performance - window.onscroll vs setInterval

What would be better solution performance-wise - executing a function every 100 ms via setInterval or executing a function when page is scrolled? I just checked and single scroll can cause a function to be executed over 50 times. Setting setInterval to 100ms would cause function to be executed only 10 times per second but on the downside the function would be executed even if the page is not scrolled.
The function is rather simple (checkes window.pageYOffset and changes style if it's over 100)
This sounds like a job for a debounce function. Such a method rate limits calls to a function.
You mention the single scroll hitting your callback over 50 times. By utilizing debounce the callback would not be invoked until the debounce function IS NOT called for a specified amount of time. (in the below example 300ms)
var scrollHandler = debounce(function() {
// your window.pageYOffset logic
}, 300);
window.addEventListener('scroll', scrollHandler);
A much more complete explanation and example debounce function can be found at:
https://davidwalsh.name/javascript-debounce-function
or
Can someone explain the "debounce" function in Javascript
Using such an approach will make a more optimized number of calls, and only when the page is interacted with (sounds like this should happen when the page is scrolled).

Is there any advantage to using requestAnimationFrame instead of setTimeout for debounce/throttle

I've come across this example on MDN that uses requestAnimationFrame instead of setTimeout:
// Reference: http://www.html5rocks.com/en/tutorials/speed/animations/
var last_known_scroll_position = 0;
var ticking = false;
function doSomething(scroll_pos) {
// do something with the scroll position
}
window.addEventListener('scroll', function(e) {
last_known_scroll_position = window.scrollY;
if (!ticking) {
window.requestAnimationFrame(function() {
doSomething(last_known_scroll_position);
ticking = false;
});
}
ticking = true;
});
And it got me thinking whether we can use requestAnimationFrame instead of setTimeout(fn, 0) and if there is any advantage to this? I've googled and it seems that all comparisons are done in the context of animations, but what about unrelated functionality - like debounce/throttle or simply if you need to run code after repaint?
RequestAnimationFrame is good if you want to make sure you don't do unnecessary work because you changed something two times between 2 frame updates.
In itself, the requestAnimationFrame is not useful for anything other than animation, because it can only wait 16.666 milliseconds (if there's no lag), thus you need to chain multiple together. But if you pair it with setTimeout, then you will be able to wait a sepcific amount of milliseconds and also make sure you draw everything in the correct time.
requestAnimationFrame is called at the time when the browser is in the repaint step. So in theory it should avoid flickering/jittering if you try to sync properties of elements (like the position) with the scroll position.
setTimeout will be called after a minimum of n milliseconds, so you callback might be called multiple times before the next repaint and you will wast CPU usage, or multiple successive repaints happen without that the callback is called which will result into flickering/jittering if you try to sync properties of the elements with the scroll position.
Apart from above answers,
When using requestAnimationFrame your animations will only run when the tab (or window) is visible to the user. This means less CPU, GPU and memory usage, hence Battery Friendly. This is especially important for mobile devices that typically have a relatively short battery life.
But for smooth animations we have to take care that our frame rendering happens in less than 16ms, so callback should be as small as possible for 60 fps animations.

How to properly set a timer for a function that positions your elements based in a formula?

I have a function that positions elements of my page. For example:
refresh_positions = function(){
set_pos(arrow_div,mouse_x,mouse_y);
set_pos(title_tiv,window_width/2,20);
};
This, obviously, must run continously, as fast as possible, in order for the elements to always be positioned correctly. But how?
If I set a fast timer like setInterval(refresh_positions,10), slower computers will freeze. If I set a slower timer, faster computers will have a worse experience. I also have a concern with battery drainage in mobile devices. What's the right way of positioning elements based on a function?
Try to use setTimeout or window.requestAnimationFrame, this ensures that new function call will only be queued when the previous function finished to run. In this way the Browser UI wont freeze that fast if the function takes longer than the interval you planned for.
var interval = <so many seconds should it take>;
function update(){
//do you stuff here
setTimeout( update, interval );
//or
window.requestAnimationFrame( update );
}
the second approach with window.requestAnimationFrame has the advantage that the is triggered up to sixty times a second if possible, or less if the browser cannot run it that fast. Also the callback is not triggered if the tab or the browser looses focus.

setTimeout or setInterval?

As far as I can tell, these two pieces of javascript behave the same way:
Option A:
function myTimeoutFunction()
{
doStuff();
setTimeout(myTimeoutFunction, 1000);
}
myTimeoutFunction();
Option B:
function myTimeoutFunction()
{
doStuff();
}
myTimeoutFunction();
setInterval(myTimeoutFunction, 1000);
Is there any difference between using setTimeout and setInterval?
They essentially try to do the same thing, but the setInterval approach will be more accurate than the setTimeout approach, since setTimeout waits 1000ms, runs the function and then sets another timeout. So the wait period is actually a bit more than 1000ms (or a lot more if your function takes a long time to execute).
Although one might think that setInterval will execute exactly every 1000ms, it is important to note that setInterval will also delay, since JavaScript isn't a multi-threaded language, which means that - if there are other parts of the script running - the interval will have to wait for that to finish.
In this Fiddle, you can clearly see that the timeout will fall behind, while the interval is almost all the time at almost 1 call/second (which the script is trying to do). If you change the speed variable at the top to something small like 20 (meaning it will try to run 50 times per second), the interval will never quite reach an average of 50 iterations per second.
The delay is almost always negligible, but if you're programming something really precise, you should go for a self-adjusting timer (which essentially is a timeout-based timer that constantly adjusts itself for the delay it's created)
Is there any difference?
Yes. A Timeout executes a certain amount of time after setTimeout() is called; an Interval executes a certain amount of time after the previous interval fired.
You will notice the difference if your doStuff() function takes a while to execute. For example, if we represent a call to setTimeout/setInterval with ., a firing of the timeout/interval with * and JavaScript code execution with [-----], the timelines look like:
Timeout:
. * . * . * . * .
[--] [--] [--] [--]
Interval:
. * * * * * *
[--] [--] [--] [--] [--] [--]
The next complication is if an interval fires whilst JavaScript is already busy doing something (such as handling a previous interval). In this case, the interval is remembered, and happens as soon as the previous handler finishes and returns control to the browser. So for example for a doStuff() process that is sometimes short ([-]) and sometimes long ([-----]):
. * * • * • * *
[-] [-----][-][-----][-][-] [-]
• represents an interval firing that couldn't execute its code straight away, and was made pending instead.
So intervals try to ‘catch up’ to get back on schedule. But, they don't queue one on top of each other: there can only ever be one execution pending per interval. (If they all queued up, the browser would be left with an ever-expanding list of outstanding executions!)
. * • • x • • x
[------][------][------][------]
x represents an interval firing that couldn't execute or be made pending, so instead was discarded.
If your doStuff() function habitually takes longer to execute than the interval that is set for it, the browser will eat 100% CPU trying to service it, and may become less responsive.
Which do you use and why?
Chained-Timeout gives a guaranteed slot of free time to the browser; Interval tries to ensure the function it is running executes as close as possible to its scheduled times, at the expense of browser UI availability.
I would consider an interval for one-off animations I wanted to be as smooth as possible, whilst chained timeouts are more polite for ongoing animations that would take place all the time whilst the page is loaded. For less demanding uses (such as a trivial updater firing every 30 seconds or something), you can safely use either.
In terms of browser compatibility, setTimeout predates setInterval, but all browsers you will meet today support both. The last straggler for many years was IE Mobile in WinMo <6.5, but hopefully that too is now behind us.
setInterval()
setInterval() is a time interval based code execution method that has the native ability to repeatedly run a specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().
If you want to loop code for animations or on a clock tick, then use setInterval().
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);
setTimeout()
setTimeout() is a time based code execution method that will execute a script only one time when the interval is reached. It will not repeat again unless you gear it to loop the script by nesting the setTimeout() object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);
If you want something to happen one time after a specified period of time, then use setTimeout(). That is because it only executes one time when the specified interval is reached.
The setInterval makes it easier to cancel future execution of your code. If you use setTimeout, you must keep track of the timer id in case you wish to cancel it later on.
var timerId = null;
function myTimeoutFunction()
{
doStuff();
timerId = setTimeout(myTimeoutFunction, 1000);
}
myTimeoutFunction();
// later on...
clearTimeout(timerId);
versus
function myTimeoutFunction()
{
doStuff();
}
myTimeoutFunction();
var timerId = setInterval(myTimeoutFunction, 1000);
// later on...
clearInterval(timerId);
I find the setTimeout method easier to use if you want to cancel the timeout:
function myTimeoutFunction() {
doStuff();
if (stillrunning) {
setTimeout(myTimeoutFunction, 1000);
}
}
myTimeoutFunction();
Also, if something would go wrong in the function it will just stop repeating at the first time error, instead of repeating the error every second.
The very difference is in their purposes.
setInterval()
-> executes a function, over and over again, at specified time intervals
setTimeout()
-> executes a function, once, after waiting a specified number of milliseconds
It's as simple as that
More elaborate details here http://javascript.info/tutorial/settimeout-setinterval
When you run some function inside setInterval, which works more time than timeout-> the browser will be stuck.
- E.g., doStuff() takes 1500 sec. to be execute and you do: setInterval(doStuff, 1000);
1) Browser run doStuff() which takes 1.5 sec. to be executed;
2) After ~1 second it tries to run doStuff() again. But previous doStuff() is still executed-> so browser adds this run to the queue (to run after first is done).
3,4,..) The same adding to the queue of execution for next iterations, but doStuff() from previous are still in progress...
As the result- the browser is stuck.
To prevent this behavior, the best way is to run setTimeout inside setTimeout to emulate setInterval.
To correct timeouts between setTimeout calls, you can use self-correcting alternative to JavaScript's setInterval technique.
Your code will have different execution intevals, and in some projects, such as online games it's not acceptable. First, what should you do, to make your code work with same intevals, you should change "myTimeoutFunction" to this:
function myTimeoutFunction()
{
setTimeout(myTimeoutFunction, 1000);
doStuff();
}
myTimeoutFunction()
After this change, it will be equal to
function myTimeoutFunction()
{
doStuff();
}
myTimeoutFunction();
setInterval(myTimeoutFunction, 1000);
But, you will still have not stable result, because JS is single-threaded. For now, if JS thread will be busy with something, it will not be able to execute your callback function, and execution will be postponed for 2-3 msec. Is you have 60 executions per second, and each time you have random 1-3 sec delay, it will be absolutely not acceptable (after one minute it will be around 7200 msec delay), and I can advice to use something like this:
function Timer(clb, timeout) {
this.clb = clb;
this.timeout = timeout;
this.stopTimeout = null;
this.precision = -1;
}
Timer.prototype.start = function() {
var me = this;
var now = new Date();
if(me.precision === -1) {
me.precision = now.getTime();
}
me.stopTimeout = setTimeout(function(){
me.start()
}, me.precision - now.getTime() + me.timeout);
me.precision += me.timeout;
me.clb();
};
Timer.prototype.stop = function() {
clearTimeout(this.stopTimeout);
this.precision = -1;
};
function myTimeoutFunction()
{
doStuff();
}
var timer = new Timer(myTimeoutFunction, 1000);
timer.start();
This code will guarantee stable execution period. Even thread will be busy, and your code will be executed after 1005 mseconds, next time it will have timeout for 995 msec, and result will be stable.
I use setTimeout.
Apparently the difference is setTimeout calls the method once, setInterval calls it repeatdly.
Here is a good article explaining the difference: Tutorial: JavaScript timers with setTimeout and setInterval
I've made simple test of setInterval(func, milisec), because I was curious what happens when function time consumption is greater than interval duration.
setInterval will generally schedule next iteration just after the start of the previous iteration, unless the function is still ongoing. If so, setInterval will wait, till the function ends. As soon as it happens, the function is immediately fired again - there is no waiting for next iteration according to schedule (as it would be under conditions without time exceeded function). There is also no situation with parallel iterations running.
I've tested this on Chrome v23. I hope it is deterministic implementation across all modern browsers.
window.setInterval(function(start) {
console.log('fired: ' + (new Date().getTime() - start));
wait();
}, 1000, new Date().getTime());
Console output:
fired: 1000 + ~2500 ajax call -.
fired: 3522 <------------------'
fired: 6032
fired: 8540
fired: 11048
The wait function is just a thread blocking helper - synchronous ajax call which takes exactly 2500 milliseconds of processing at the server side:
function wait() {
$.ajax({
url: "...",
async: false
});
}
Both setInterval and setTimeout return a timer id that you can use to cancel the execution, that is, before the timeouts are triggered. To cancel you call either clearInterval or clearTimeout like this:
var timeoutId = setTimeout(someFunction, 1000);
clearTimeout(timeoutId);
var intervalId = setInterval(someFunction, 1000),
clearInterval(intervalId);
Also, the timeouts are automatically cancelled when you leave the page or close the browser window.
To look at it a bit differently: setInterval ensures that a code is run at every given interval (i.e. 1000ms, or how much you specify) while setTimeout sets the time that it 'waits until' it runs the code. And since it takes extra milliseconds to run the code, it adds up to 1000ms and thus, setTimeout runs again at inexact times (over 1000ms).
For example, timers/countdowns are not done with setTimeout, they are done with setInterval, to ensure it does not delay and the code runs at the exact given interval.
You can validate bobince answer by yourself when you run the following javascript or check this JSFiddle
<div id="timeout"></div>
<div id="interval"></div>
var timeout = 0;
var interval = 0;
function doTimeout(){
$('#timeout').html(timeout);
timeout++;
setTimeout(doTimeout, 1);
}
function doInterval(){
$('#interval').html(interval);
interval++;
}
$(function(){
doTimeout();
doInterval();
setInterval(doInterval, 1);
});
Well, setTimeout is better in one situation, as I have just learned. I always use setInterval, which i have left to run in the background for more than half an hour. When i switched back to that tab, the slideshow (on which the code was used) was changing very rapidly, instead of every 5 seconds that it should have. It does in fact happen again as i test it more and whether it's the browser's fault or not isn't important, because with setTimeout that situation is completely impossible.
The difference is obvious in console:
Just adding onto what has already been said but the setTimeout version of the code will also reach the Maximum call stack size which will stop it from functioning. Since there is no base case for the recursive function to stop at so you can't have it run forever.
If you set the interval in setInterval too short, it may fire before the previous call to the function has been completed. I ran into this problem with a recent browser (Firefox 78). It resulted in the garbage collection not being able to free memory fast enough and built up a huge memory leak.
Using setTimeout(function, 500); gave the garbage collection enough time to clean up and keep the memory stable over time.
Serg Hospodarets mentioned the problem in his answer and I fully agree with his remarks, but he didn't include the memory leak/garbage collection-problem. I experienced some freezing, too, but the memory usage ran up to 4 GB in no time for some minuscule task, which was the real bummer for me. Thus, I think this answer is still beneficial to others in my situation. I would have put it in a comment, but lack the reputation to do so. I hope you don't mind.
The reason why Option A and Option B seem like they work the same is mostly because the places of the setInterval and the setTimeout functions.
function myTimeoutFunction()
{
doStuff();
setTimeout(myTimeoutFunction, 1000);
}
myTimeoutFunction();
This one is a recursive function, and if doStuff is very complex, setTimeout has to keep track of all calls of the setTimout plus the current doStuff, which makes it become slower and s l o w e r.
function myTimeoutFunction()
{
doStuff();
}
myTimeoutFunction();
setInterval(myTimeoutFunction, 1000);
On the other hand, the setInterval only has to keep track of the last setInterval and the current doStuff, making it staying at a constant speed.
So which one should you use?
From the above, you should probably be able to conclude that the better one is setInterval.
The important point to consider is the performance.
The only way to run a function periodically using setTimeout is to call it recursively with the target function, and when you check it, it appears that it works asynchronously put when you see the call stack you will find it keep growing by the time. In fact, it is sensible. Since Javascript does not support multi-threading, it is impossible to finish calling the parent function before finishing the child function, therefor, the stack will keep growing as long as there is recursive calling.
Whilst, with setInterval we don't need to call the target function recursively since it has a logic that runs it periodically as a loop. So, this keeps the call stack clean.
You can watch the call stack using developer's tools in your browser and you will notice the difference.
The difference will be clear when using small interval for a long period of time.
I think SetInterval and SetTimeout are different. SetInterval executes the block according to the time set while, SetTimeout executes the block of code once.
Try these set of codes after the timeout countdown seconds:
setInterval(function(e){
alert('Ugbana Kelvin');
}, 2000);
and then try
setTimeout(function(e){
alert('Ugbana Kelvin');
}, 2000);
You can see the differences for yourself.

Categories

Resources