Chapter 11 · Beyond the DOM
Timers and delays
Lots of things on a page happen later: a "Saved!" message that disappears after two seconds, a clock that ticks every second, an exam countdown, a search that waits until you stop typing. In this chapter you'll learn to make code wait, repeat, count down and calm down, with times written the way you'd say them.
Why not milliseconds?
JavaScript measures time in milliseconds: thousandths of a second. So plain JavaScript asks you to do maths, and to remember which comes first:
Plain JavaScript
setTimeout(() => {
print("Hello");
}, 120000);Is 120000 two minutes or twenty? You have to work it out.
Nyx
nyx.after("2 minutes", () => {
print("Hello");
});Reads like a sentence: after 2 minutes, do this.
Every Nyx tool that needs a time, including the animations from Animation and the timeouts from Servers and AJAX, understands the same plain words.
Writing a time
Write a number and a unit, in quotes. Short and long names both work, with or without a space:
"500ms", "500 milliseconds""2s", "2 sec", "2 secs", "2 seconds", "1 second""5m", "5 min", "5 mins", "5 minutes", "1 minute""1h", "1 hr", "2 hrs", "2 hours", "1 hour""1d", "3 days", "1 day""1w", "2 weeks", "1 week"A few more ways that all work:
"a minute", "an hour"One minute, one hour."1.5 hours"An hour and a half. Decimals are fine."1 minute 30 seconds"Mix units, with or without "and": "1h 30m", "2 minutes and 5 seconds".500A plain number, without quotes, means milliseconds, like plain JavaScript.nyx.time() turns a time into milliseconds, which is handy for checking:
Watch the Output below.
The last line has a typo, so Nyx tells you it can't read it, and suggests ways to write it.
Later, once: nyx.after
nyx.after() runs some code once, after a while:
nyx.after(after
"2 seconds",this long
() => { ... }run this
)Done
A "Saved!" message that disappears by itself. Click Save:
Saved!
The rest of the page doesn't stop while Nyx waits. You can keep clicking and scrolling; the code inside simply runs when its time comes.
Give it a function, not a result
This is the most common timing mistake, so it gets its own section. nyx.after() needs instructions to follow later, which is what () => { ... } is. If you write the code on its own, it runs straight away:
Runs now
nyx.after("2 seconds", print("Hi"));print("Hi") runs immediately, and Nyx gets nothing to run later.
Runs later
nyx.after("2 seconds", () => print("Hi"));() => wraps it up, to be opened in 2 seconds.
Try both. Nyx spots the first one and explains it:
Watch the Output below.
The time comes first, then the function. If you swap them, as in plain JavaScript's setTimeout, Nyx tells you that too.
Changing your mind: .stop()
nyx.after() gives back a timer. Keep it in a variable, and you can call .stop() on it before the time runs out. That's how "Undo" buttons work: the message isn't really deleted until five seconds have passed. Click Delete, then Undo:
Message: Meeting at 5 pm
let timer;An empty box for the timer, made outside both listeners so both can use it.timer = nyx.after(...)Start the 5 seconds and keep the timer.timer.stop();Cancel it. The code inside never runs.
Again and again: nyx.every
nyx.every() runs code over and over, with the same gap each time. It tells your function which time this is: 1, 2, 3 and so on. Here it stops itself after the fifth time:
Watch the Output below.
nyx.every() runs forever, even if nothing on the page shows it. Always keep the timer and call .stop() when you're done.
A clock with Start and Stop
A clock that starts and stops with buttons. Press Start twice and see that it still ticks once a second:
--:--:--
const now = new Date().toLocaleTimeString();Plain JavaScript for "the time right now", written the way the visitor's computer likes it.if (clock) clock.stop();Without this, every click on Start would add another clock, and the page would do the work twice, three times, and so on.showTime();nyx.every()waits a whole second before its first run, so we show the time once straight away.nyx.every("1 second", showTime)You can pass a function's name instead of() => { ... }. Notice: no()aftershowTime, for the same reason as in Give it a function, not a result above.
Browsers slow timers down in tabs you aren't looking at, to save battery. A clock catches up when you come back, because it reads the real time each tick.
Pausing: await nyx.wait
To do several things one after another, with pauses in between, use await nyx.wait(). It reads from top to bottom, like a recipe:
Ready?
await only pauses this piece of code. Buttons, scrolling and other code keep working. And, as you learned in Servers and AJAX, await only works inside an async function:
nyx("#go").on("click", async () => {
nyx("#light").text("Red");
await nyx.wait("2 seconds");
nyx("#light").text("Green");
});await nyx.wait("1 second")Pausing any code: messages, steps, requests.nyx("#box").fadeOut().wait("1 second").fadeIn()A pause between animations in a chain, from Animation.Counting down: nyx.countdown
nyx.countdown() counts down to a moment, and tells you every second how much time is left:
nyx.countdown(count down
"10 seconds",to when
(left) => { ... },every second
() => { ... }at the end
)Done
10s
Every second, left holds:
left.textReady to show, like "2d 4h 15m 9s". Bigger units only appear when they're needed, so the last few seconds read "9s".left.daysWhole days left.left.hoursHours left, after the days: 0 to 23.left.minutesMinutes left, after the hours: 0 to 59.left.secondsSeconds left, after the minutes: 0 to 59.left.totalEverything left, in milliseconds.Counting down to a date
Instead of a length of time, give it a date and time, written as year-month-day, a T, then the time in 24-hour format:
nyx.countdown("2027-02-15T10:00", (left) => {
nyx("#exam").text(left.days + " days to the exam");
}, () => {
nyx("#exam").text("Good luck!");
});Like the other timers, it gives back a timer with .stop(). Make your own: change the date below to your birthday, or any moment in the future:
…
Write "2027-02-15", not "15/02/2027". Different countries put the day and month in different orders, so computers only trust year-month-day. If Nyx can't read a date, it tells you.
Wait until they stop: nyx.debounce
Some events fire very often. Typing "Kolkata" fires seven input events, but a search only needs to run once, when the typing stops. Think of a lift: the doors wait until people stop walking in, then close.
nyx.debounce() wraps a function so it only runs after things have gone quiet for a while. Type in the box and compare the two counts:
Runs on every key: 0
Runs with debounce: 0
nyx.debounce(wait for quiet
"400ms",this long
() => { ... }then run this
)Done
You used this in Servers and AJAX for search as you type. It's also good for saving a draft when someone stops writing, or redrawing after a window stops resizing.
Not too often: nyx.throttle
Sometimes you want updates while something is happening, just not hundreds of them. Moving the mouse or scrolling fires dozens of events a second. nyx.throttle() lets the function run at most once in each period. Move your mouse (or finger) over the box:
Runs on every move: 0
Runs with throttle: 0
nyx.debounce("400ms", fn)Once, after it stops. For typing in a search box, saving drafts, resizing.nyx.throttle("250ms", fn)Regularly, while it goes on. For scrolling, dragging, moving the mouse.Putting it together
A quick quiz with a 15-second limit. The countdown runs while you think; answering stops it, and running out of time locks the answers:
What is the capital of India?
15s
const timer = nyx.countdown(...)Start the 15 seconds and keep the timer, so we can stop it.answers.prop("disabled", true)When time runs out, nobody can click an answer any more.timer.stop();Clicking an answer stops the countdown where it is.button.is("[data-right]")Is the clicked button the right one? You met.is()in Moving around.nyx.after("3 seconds", ...)Let the result fade away after a moment.
Common mistakes
nyx.after("2 seconds", () => print("Hi")), not print("Hi") on its own.nyx.after("2 seconds", fn).if (clock) clock.stop();nyx.every() runs until .stop(). Keep the timer in a variable.nyx.after(5, fn) runs instantlyA plain number means milliseconds. Write "5 seconds"."2027-02-15T10:00".async to the function around await nyx.wait().Exercise
Fill in the blanks, then press Check answers.
1. Hide the notice once, after 3 seconds.
nyx.("3 seconds", () => nyx("#notice").hide());
2. Check for new messages every 30 seconds.
nyx.("30 seconds", checkMessages);
3. Cancel the timer.
timer.();
4. Pause for one second inside an async function.
await nyx.("1 second");
5. Search only after the typing stops.
nyx("#q").on("input", nyx.("300ms", search));
6. Update a progress bar at most every 100ms while scrolling.
nyx(window).on("scroll", nyx.("100ms", update));
7. Count down to 15 February 2027 at 10 am.
nyx.countdown("", showLeft);
Remember
"500ms", "2 seconds", "1 minute 30 seconds". A plain number means milliseconds.nyx.after() runs once, later. nyx.every() runs again and again.() => { ... } or a function's name without ()..stop(). Keep it in a variable, and stop old timers before starting new ones.await nyx.wait() pauses steps, inside an async function.nyx.countdown() counts to a length of time or a year-month-day date, and gives you left.text every second.nyx.debounce() runs once things stop. nyx.throttle() runs regularly while they go on.