如何在一定时间后杀死Javascript函数

Eva*_*one 3 html javascript

当用户开始滚动滚动条时,我有一个页面开始自动滚动.但我希望滚动在一段时间后停止.以下是我到目前为止但它没有工作.我不认为"回归"; 是我应该使用的正确功能,但我找不到任何有用的功能.

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

window.onscroll = scrollFunction;

setTimeout(function scrollFunction() {
    return;
}, 2000);
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

Fel*_*ing 5

您创建的两个函数彼此无关.它们具有相同名称的事实无关紧要.

setTimeout用于安排将来的一些工作.但是你传递给setTimeout它的功能完全没有做任何事情,所以这是不必要的.

相反,您必须跟踪第一次调用函数的时间,并检查每次调用函数时经过了多长时间.如果已经过了足够的时间,请不要window.scrollBy(0, 10)再次调用以防止重新触发事件.

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;
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)