There is a function that starts when the page is scrolled to a specific place (for example, up to ( top>800 ) If we scroll the page back (( top<800 ), the function will continue to run until it is completely completed.
Question: How to make the function stop if the condition is no longer satisfied? It looks like this:
function add() { $("ul li").each(function(i, el) { setTimeout(function() { $(el).addClass("active"); }, 0 + (i * 800)); }); } function remove() { $("ul li").each(function(i, el) { $(el).removeClass("active"); }); } $(window).scroll(function() { var top = $(window).scrollTop(); if (top > 300) { add(); } else { remove() } }) body { height: 2800px; } ul { display: block; position: fixed; } li { background: #FF9800; margin: 2px; display: inline-block; padding: 5px; color: #fff; } li.active { background: #8BC34A; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> </ul>
elsemeans addcl - not running and there is nothing to interrupt - Grundy