Javascript how to stop setTimeOut

谁说我不能喝 提交于 2019-12-23 05:07:10

问题


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!!

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();
}

回答1:


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.

Basically, in this day and age, we want the browser/CSS to do the transition. It's less code, and using transform it will be much smoother.

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);
}



回答2:


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(). 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. 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.


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.

For example:

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


来源:https://stackoverflow.com/questions/34845844/javascript-how-to-stop-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!