0

my function causes a sluggish behaviour of scrolling

$(function() {
    var currentHash = "top";
    $(document).bind('scroll', function(e) {
        $('.content section, .scrollpos').each(function() {
            var hash = $(this).attr('data-anchor');
            if (
                $(this).offset().top < window.pageYOffset + 330 && $(this).offset().top + $(this).height() > window.pageYOffset + 330 && currentHash != hash
            ) {
                if (history.pushState) {
                    history.pushState(null, null, "#" + hash);
                } else {
                    window.location.hash = '#myhash';
                }
            }
        });
    });
});

I read about a debounce function (https://davidwalsh.name/javascript-debounce-function), but unfortunately I can not make it work with my function.

Can somebody please give me a hint how to implement the debounce to the function? thank you in advance!

rrk
  • 15,677
  • 4
  • 29
  • 45
user2814794
  • 81
  • 1
  • 1
  • 7
  • You should be using requestAnimationFrame for this kind of tasks, especially if you're planning to update some visuals as well. – spectras Apr 02 '16 at 09:35
  • thank you for your answer! whats the difference in using a debounce function or the requestAnimationFrame? Unfortunately I can't get both running ... – user2814794 Apr 02 '16 at 12:22
  • rAF will synchronise with browser refresh. It allows to update things in the page right before the browser repaints all. See http://stackoverflow.com/questions/5605588/how-to-use-requestanimationframe for an example. Granted, it's only useful if you want to update things. Otherwise, debouncing is a better idea. – spectras Apr 02 '16 at 16:43
  • Thank you for this explanation! Actually updating is not necessery, it's just about changing the history.pushState. Could you help me implement the function in the debounce function? By just copy and paste nothing happens ... – user2814794 Apr 03 '16 at 10:02

0 Answers0