简体   繁体   English

无法通过同步睡眠在 Javascript 上滚动

[英]Can't scroll on Javascript with synchronous sleep

I'am writting a code to scroll down with synchronous pauses between scrolls.我正在编写代码以在滚动之间同步暂停向下滚动。 To achieve synchronous sleep I am using the classic Javascript approach using a While loop with a timer.为了实现同步睡眠,我使用了经典的 Javascript 方法,使用带有计时器的 While 循环。 Here's where it gets wierd, the function works with everything except for scrolling.这就是它变得奇怪的地方,该功能适用于除滚动之外的所有内容。

ex 1. This WORKS: ex 1. 这有效:

function sleep(t) {
  const start = Date.now();
  while (Date.now() - start < t);
}

console.log("hello")
sleep(2000);
console.log("hello 2")
sleep(2000);
console.log("hello 3")
sleep(2000);
console.log("hello 4")
sleep(2000);

Ex 2. This does NOT WORK:例 2。这不起作用:

function sleep(t) {
  const start = Date.now();
  while (Date.now() - start < t);
}
elem = document.getElementById("main-div");
elem.scrollBy(0,120);
sleep(2000);
elem.scrollBy(0,120);
sleep(2000);
elem.scrollBy(0,120);
sleep(2000);
elem.scrollBy(0,120);
sleep(2000);

Any Idea what is happening?知道发生了什么吗?

I am not sure what you mean by "the code is wrapped in some python script", this in a browser environment.我不确定你所说的“代码被包裹在一些 python 脚本中”是什么意思,这是在浏览器环境中。 When you run JS code it blocks the current browser window, eg all async actions like user interactions, scrolling, timer callbacks are paused until you yield back to the event loop, and give other events in the queue a chance to run.当您运行 JS 代码时,它会阻塞当前浏览器窗口,例如,所有异步操作(如用户交互、滚动、计时器回调)都会暂停,直到您退回到事件循环,并让队列中的其他事件有机会运行。

Instead of blocking the event loop you could start an interval timer, and disable actions you'd like to prevent from happening until the time is over.您可以启动一个间隔计时器,而不是阻止事件循环,并在时间结束之前禁用您想要防止发生的操作。

Here is an example: When you click on the "Busy for 8 sec" button, the other "Submit" button is disabled until the time is over, or until you hit the "Busy for 8 sec" button again to stop the timer.这是一个示例:当您单击“忙 8 秒”按钮时,另一个“提交”按钮将被禁用,直到时间结束,或者直到您再次单击“忙 8 秒”按钮以停止计时器。

 $('document').ready(function() { $('#busyButton').click(function() { if(timerId) { stopTimer(); return; } else { startTimer(); } }); }); let timerId; function startTimer() { $('#submitButton').prop("disabled", true).css({color: 'gray'}); $('#busyButton').css({color: 'red'}); let count = 0; timerId = setInterval(function() { console.log('count', ++count); if(count >= 8) { stopTimer(); } }, 1000); } function stopTimer() { clearInterval(timerId); timerId = null; $('#submitButton').prop("disabled", false).css({color: 'black'}); $('#busyButton').css({color: 'black'}); }
 .as-console-wrapper { max-height: 7em;important; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input /> <button id="submitButton">Submit</button> <hr /> <button id="busyButton">Busy for 8 sec</button>

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

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