How do I only console.log when the value is different from the previous value?

Viewed 225

How do I only console.log(finalPercentage); when the value is different from what it previously was?

Each time I scroll it console logs the same number about 43 times until it changes. I just want it to console.log the number when it changes value.

Is this possible?

 scroll.on('scroll', (position) => {
    let pageHeight = $('body').height() - $(window).height();
    let scrollPos = position.scroll.y;
    let scrollPercentage = (scrollPos * 100) / pageHeight;
    let finalPercentage = Math.ceil(scrollPercentage);

    console.log(finalPercentage);
 }    
2 Answers

You use public a variable.

let prevValue = null;
scroll.on('scroll', (position) => {
    let pageHeight = $('body').height() - $(window).height();
    let scrollPos = position.scroll.y;
    let scrollPercentage = (scrollPos * 100) / pageHeight;
    let finalPercentage = Math.ceil(scrollPercentage);
    if(prevValue == finalPercentage) return;
    prevValue = finalPercentage;
    console.log(finalPercentage);
} 

Yes it is possible. You just need to keep track of the last value then compare it each time you want to decide whether or not to output to the console. Like so:

let lastValue = 'Some initial value';
scroll.on('scroll', (position) => {
    let newValue = 'Get new value';
    if (lastValue != newValue)
        console.log(newValue);
    lastValue = newValue;
});
Related