Subj : setInterval() and setTimeout()
To : Nightfox
From : echicken
Date : Fri Feb 25 2022 06:09 am
Re: setInterval() and setTimeout()
By: Nightfox to echicken on Thu Feb 24 2022 20:58:32
Ni> Hmm.. I'm wondering if setInterval() and setTimeout() can be used as I
Ni> expected. I was thinking I could use those to have a function be called
Ni> while my script is doing other things. Say, for example, in SlyEdit, if I
Ni> wanted it to udpate the time in the corner of the screen at a regular
Ni> interval, I was thinking I could use setInterval() to have it run a
Ni> function to do that at a regular interval (while the user is still editing
Ni> a message). But with the behavior you describe, I'm not sure if that would
Ni> be possible?
I don't think it's possible yet.
You're probably taking input from the user via console.getkey inside of a loop. You may be doing this in a single main loop, or in several places. Any such loop will block the script and prevent timers from running.
The solution would be to have your script define a bunch of functions, etc., register a callback that gets fired when the user hits a key, and then simply exit without blocking / looping. At this point everything flows from your timers and input handler. Now your timers are free to run, and won't be blocked except maybe briefly by your input callback. Unless SlyEdit was designed in a very modular way, this probably means a huge refactoring.
Even if you had the appetite to do this work, there's a catch: there is no "user input" event, and no way to register that crucial callback. You could probably fake this by using console.inkey in a setInterval, but that's getting pretty nasty.
I'm using SlyEdit right now, and I noticed that if I pause for a minute, the clock doesn't update until I hit a key. So I imagine you're using console.getkey. Here's an easier solution to updating the clock on a schedule:
load('event-timer.js');
const t = new Timer();
function updateClock() {
// do stuff here
}
function getKey() {
var k;
while (!k && !js.terminated) {
t.cycle();
k = console.inkey(K_NONE, 25);
}
return k;
}
t.addEvent(1000, true, updateClock);
Obviously simplistic, but the idea would be to use the custom getKey function as a drop-in replacement for console.getkey. Now you've got a timer that will be allowed to run while you wait for user input.