Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop a function after ten seconds?

I found this piece of code while trying to find out a way to load a reddit page so that I can use ctrl + f to find a specific post. The problem is that it just keeps scrolling down and loading the pages. I need to find a way to stop it after 10 seconds so that I can take a look at what I loaded. Also I don't know any javascript so I couldn't really find anythig that would help me.

Here is the code

var lastScrollHeight = 0;
function autoScroll() {
  var sh = document.documentElement.scrollHeight;
  if (sh != lastScrollHeight) {
    lastScrollHeight = sh;
    document.documentElement.scrollTop = sh;
  }
}
window.setInterval(autoScroll, 100);

I just paste that into the firefox console.

like image 367
leo Avatar asked Feb 17 '26 12:02

leo


2 Answers

To stop the interval after a certain amount of time use a setTimeout() that calls clearInterval(). Here's a simplified version (with the time reduced to 1 second for demo purposes) that should help:

function autoScroll(){
  console.log("running")
}

// save a reference to the interval handle
let interval = window.setInterval(autoScroll, 100);

// cancel interval after 1 second (1000 ms)
setTimeout(() => clearInterval(interval), 1000)
like image 122
Mark Avatar answered Feb 20 '26 00:02

Mark


The setInterval() function returns an ID, which you can use to stop it. Just put it in setTimeout() method like this:

var myInterval = setInterval(autoscroll, 100);
setTimeout(function(){ clearInterval(myInterval); }, 10000);
like image 45
Slawomir Wozniak Avatar answered Feb 20 '26 00:02

Slawomir Wozniak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!