Javascript how to set time interval to stop scrolling

This is a demo in jsfiddle, a demo

I want the scrollable elements ("one", "two", "three", "4", "5", "6", "7") to automatically scroll up, as shown by the demo, and stop for 2 seconds when it is in the middle position. But in my demonstration, he will caress for some time after stopping in the middle position.

Here is the place in my demo code to set the position.

if ((x == 0) || (x % 35== 0)) { setTimeout(function () { i.top = x + 'px'; }, 1000); } else { i.top = x + 'px'; } 

Can anybody help me? Thanks!

UPDATE: The reason I set 35 is because I found that the scrolled elements are approximately in the middle position when they are 0, -35, -70, -105, .... But when I console everything x, I found that the value of x is between (31, -251). Do you know how to find the exact position when each element is in the middle of the position? Thank you

+5
source share
1 answer

I changed your code a bit,

i sets the variable "k" to which the interval is assigned, and I clear the interval when stopped and start it again after a timeout

looks good to me → http://jsfiddle.net/ato0mf7u/3/ no funny shakin anymore ;-D

 window.onload = addScrollers; var i = 1; var arr = ['one ', 'two', 'three', '4', '5', '6', '7']; var mid; var k; function addScrollers() { var txt = arr[0]; while (i < arr.length) { txt += '<p>' + arr[i] + '</p>'; i++; } startScroll('myscroller', txt); } var speed = 10; // scroll speed (bigger = faster) var dR = false; // reverse direction var step = 1; function objWidth(obj) { if (obj.offsetWidth) return obj.offsetWidth; if (obj.clip) return obj.clip.width; return 0; } function objHeight(obj) { if (obj.offsetHeight) return obj.offsetHeight; if (obj.clip) return obj.clip.height; return 0; } function scrF(i, sH, eH) { var x = parseInt(i.top) + (dR ? step : -step); if (dR && x > sH) { x = -eH; } else if (x < 1 - eH) { x = sH; } //when x is the times of 35, the positio is in middle if ((x == 0) || (x % 35== 0)) { clearInterval(k); setTimeout(function () { i.top = x + 'px'; k = setInterval(function () { scrF(i, sH, eH); }, 1000 / speed); }, 1000); } else { i.top = x + 'px'; } return x; } function startScroll(sN, txt) { var scr = document.getElementById(sN); var sW = objWidth(scr); var sH = objHeight(scr); scr.innerHTML = '<div id="' + sN + 'in" style="position:absolute; left:3px; width:' + sW + ';">' + txt + '<\/div>'; var sTxt = document.getElementById(sN + 'in'); var eH = objHeight(sTxt); mid = (eH - sH) / 2; sTxt.style.top = (dR ? -eH : sH) + 'px'; sTxt.style.clip = 'rect(0,' + sW + 'px,' + eH + 'px,0)'; k = setInterval(function () { scrF(sTxt.style, sH, eH); }, 1000 / speed); } 
+3
source

Source: https://habr.com/ru/post/1202685/


All Articles