Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill Javascript function after a certain amount of time [duplicate]

I have a page that begins to scroll automatically when the user begins to scroll the scrollbar. But I want the scrolling to stop after a certain amount of time. Below is what I have so far but it is not working. I don' think that "return;" is the right function I should be using but I can't find anything that does work.

function scrollFunction() {
  window.scrollBy(0, 10);
}

window.onscroll = scrollFunction;

setTimeout(function scrollFunction() {
    return;
}, 2000);
<div style="height:1000px; background-color:red;"></div>
<div style="height:1000px; background-color:green;"></div>
<div style="height:1000px; background-color:blue;"></div>
<div style="height:1000px; background-color:black;"></div>
like image 650
Evan Gladstone Avatar asked Mar 08 '23 18:03

Evan Gladstone


1 Answers

The two functions you created have nothing to do with each other. The fact that they have the same names is irrelevant.

setTimeout is used to schedule some work in the future. But the function you pass to setTimeout doesn't do anything at all, so it's unnecessary.

Instead, you have to keep track of when the function was called the first time and check how much time has passed every time the function is called. If enough time has passed, don't call window.scrollBy(0, 10) again to prevent re-triggering the event.

var startTime;
function scrollFunction() {
  if (!startTime) {
    // Called for the first time
    startTime = Date.now();
  } else if (Date.now() - startTime > 2000) {
    // Stop condition. Have 2 seconds passed?
    startTime = null;
    return;
  }
  window.scrollBy(0, 10);
}

window.onscroll = scrollFunction;
<div style="height:1000px; background-color:red;"></div>
<div style="height:1000px; background-color:green;"></div>
<div style="height:1000px; background-color:blue;"></div>
<div style="height:1000px; background-color:black;"></div>
like image 115
Felix Kling Avatar answered Mar 10 '23 08:03

Felix Kling