I don't know if window.scrollTo
has a duration in the option because it's all JSON and the API isn't clearly documented anywhere.
for (i = 0; i < 1000; i++) {
var sine = Math.sin(i/10);
var scroll = sine * 1000;
console.log(scroll);
window.scrollTo({top: scroll, left: 0, behavior: 'smooth' });
}
I'd like a page to scroll up and down continuously, but this doesn't seem to work. Instead of executing all of the instructions in order, like you think it would, it consoles all values, then does a scroll at the end.
There's also no sensible sleep
function in JavaScript. Also, the duration of this scroll is totally arbitrary.
How should I try to do such a seemingly simple task in JavaScript?
I would think of doing something like this in pseudo-code:
i = 0;
while (true) {
scroll = sine(i);
scrollTo(sine);
// if scrollTo is asynchronous or something.
sleep(x); // x how ever long scroll takes.
i += 1;
}
But there is no sleep
function in JS, the execution isn't even in order, and I have no idea how long x
takes.
EDIT:
Still no solution found.
https://codepen.io/waterwaltz/pen/gbOdQb/
This codepen demos a possible way with the following:
function loop() {
$("html, body").animate({ scrollTop: "0" }, 1000).animate({scrollTop: "100"}, 1000, loop)
}
But there's no way to exit the loop! Because 1) JS global variables don't work at all and 2) passed variables also don't work (a callback with no parameters? Who wrote this language?)
The only example with a stoppable loop I can find is here:
https://codepen.io/gabrieleromanato/pen/jEfbn
But it uses CSS animations that don't scroll!
I love JavaScript!
EDIT 2:
It's even worse.
var thing = "GO";
window.setInterval(function() {
console.log(thing);
if (thing == "GO") {
$("html, body").animate({ scrollTop: "0" },1000)
$("html, body").animate({ scrollTop: "1000" },1000)
}
});
Running this with thing
initially set to "GO"
will result in a scroll loop, and even consoles "GO"
, but then setting thing
to "NO"
(or something else), doesn't just not stop the loop, but consoles "NO"
while keeping the loop going!
I'm now at a total loss.