Skip to content
Advertisement

Clicking on a button or at the current position of mouse using JavaScript to keep Google Colab notebook alive

I am trying to keep the Google Colab notebook alive for few hours even if I go out for some time. People who have no idea should only know that if you don’t manually intervene then the processes stop and all of your work is lost.

I want my mouse to keep clicking at the current position 12 hours at an interval of 15 minutes. This would be the best case for me. Also IF I can add a bit of scroll up and down both without affecting the position of my mouse would be nice. Obviously, I did nit know how to do that so I went for other options as selectiong an element that is clickable and click it for some time. HAd it been Python and Selenium I would have done it but somehow I could select a position and wrote a code as:

run_buttons = document.getElementsByTagName('colab-run-button')

for (i = 0; i < 50; i++) {setTimeout(() => { run_buttons[run_buttons.length-1].click() ; }, 100);
}

Problem is that it is clicking so fast without a time interval. How can I apply Python style time.sleep() so that the code inside console click on the button for 12 hours at an interval of 20 minutes.

Advertisement

Answer

First of all, you are not waiting for a given timeout to complete before queuing next timeout. You will need to properly handle asynchronous behavior of timeouts to accomplish what you want.

Instead, you can use setInterval instead of setTimeout and notice both of these functions take time in ms milliseconds not s seconds. setInterval calls the given callback after specified ms repeatedly. So:

var keepAliveInterval = setInterval(() => { play_buttons[43].click() ; }, 15 * 60 * 1000); // 15 * 60 * 1000 = 15 minutes in milliseconds

To stop this interval, you can have a single timeout of:

setTimeout(() => { clearInterval(keepAliveInterval) }, 24 * 60 * 60 * 1000); // 24 * 60 * 60 * 1000 = 24 hours in milliseconds
Advertisement