Ad

Javascript How To Stop SetTimeOut

- 1 answer

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

Ad

Answer

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);
}
Ad
source: stackoverflow.com
Ad