javascriptcinnamon

Run code every "x" seconds without setInterval


I'm writing a Cinnamon panel applet (in JavaScript) that polls a set command for information every 20-120 seconds, set by the user. But the problem is that setInterval does not exist in the subset (?) of JavaScript that Cinnamon applets use. I tried to use this:

function sleep(milliseconds) {
    const date = Date.now();
    let currentDate = null;
    do {
      currentDate = Date.now();
    } while (currentDate - date < milliseconds);
}

This doesn't work, as it locks up the whole panel for milliseconds except for a moment while it's running.

while (true) {
    sleep(seconds*1000)
    this.set_applet_label(cmd_output)
}

This is the code for the loop I'm using. What I need is some kind of non-blocking way to run code every X seconds in JavaScript.


Solution

  • Discovered by @blex By importing Mainloop, you can get a timeout_add_seconds function: https://github.com/axos88/cinnamon-countdown-timer/blob/master/applet.js#L213