简体   繁体   English

Javascript如何停止setTimeOut

[英]Javascript how to stop setTimeOut

Hellow I ran into a little problem i don't know how to stop my add function when it reaches some Y position on my web, can some body help me whit it!! 您好,我遇到了一个小问题,我不知道如何在我的添加功能到达网络上的某些Y位置时停止我的添加功能,某些机构可以帮助我吗!

 var scroll = function(){ var positionYTop = 0, speed = 50, links = document.getElementsByTagName('a'); function timer() { var clock = setTimeout(add, 200) } function add() { window.scrollTo(0, positionYTop += speed); timer(); } add(); } 

It's not clear exactly what you're trying to do with your specific code, but the general answer for stopping a timer is that you save the result from setTimeout() into a variable that is in a high enough scope or on a property of an object that you can later access it and then use it to call clearTimeout() . 尚不清楚您要使用特定的代码做什么,但是停止计时器的一般答案是将setTimeout()的结果保存到范围足够大或变量的属性中对象,您以后可以访问它,然后使用它来调用clearTimeout() That will stop the timer. 那将停止计时器。

In your current code, the variable clock is local only to the timer() function so as soon as that function finishes, it will be out of scope and unreachable. 在您当前的代码中,可变clock仅在timer()函数中是本地的,因此一旦该函数完成,它将超出范围且不可访问。 You likely need to move the clock variable to a higher scope where it will be accessible from whatever code you want to stop the timer from. 您可能需要将clock变量移到更高的范围,在该范围内可以从您要停止计时器的任何代码中访问它。


Or, if the issue you're asking about is how to tell your add() function to stop issuing new timer() calls when it has reached a certain position, then you can just add an if() statement to your add() function and not call timer() again if some condition has been met. 或者,如果你问的问题是,如何告诉你add()函数停止发放新的timer()调用时,它已经达到了一定的位置,那么你可以只添加一个if()语句你add()函数,如果满足某些条件,则不要再次调用timer()

For example: 例如:

function add() {
    window.scrollTo(0, positionYTop += speed);
    if (window.scrollTop < 400) {
        timer();
    }
}

A common approach to this is to start off by setting the scroll in advance, along with a transform/translateY in the other direction to offset the effect of the scroll, then transition the transform down to zero. 一种常见的方法是通过预先设置滚动开始,并在另一个方向上进行transform / translateY以抵消滚动的效果,然后将变换向下转换为零。

Basically, in this day and age, we want the browser/CSS to do the transition. 基本上,在这个时代,我们希望浏览器/ CSS进行过渡。 It's less code, and using transform it will be much smoother. 它的代码更少,使用transform会更加流畅。

Here's a very rough idea (not tested, you will need to play with it): 这是一个非常粗糙的想法(未经测试,您需要使用它):

body.start {
  transform: translateY(-400px);
}

body.transitioned {
  transform: translateY(0);
  transition: transform 1s;
}

function scroll() {
  document.body.scrollTop; = 400;
  document.body.classList.add('start');
  setTimeout(function() { document.body.classList.add('transitioned'); }, 100);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM