the modal1
setTimeout()
Using setTimeout()
is a function that calls another function after a specified amount of time.
The time is measured in milliseconds. It takes two parameters: the function being called and the number of milliseconds to wait before running the function.
setTimeout(funcName, 4000);
Above funcName
is the name of the function and it won’t run until after the time, 4s here, has elapsed.
There are no brackets following the function name. If there were it would simply run immediately. It’s a callback function. However without brackets there is nowhere to add parameters.
Adding parameters requires slightly different syntax.
It’s commonly used with an arrow function like so:
setTimeout(() => {
// some code or a function name...
}, 4000);
or on one line without the curly braces:
setTimeout(() => nuDiv.remove(), 3000);
However while these will work there is a problem when it comes to stopping them. setInterval()
and setTimeout()
are stopped using clearInterval()
and clearTimeout()
respectively. These methods require an ID of the inverval or timeout functions before they can stop them. For example:
let myTimer = setTimeout(() => nuDiv.remove(), 3000);
This will still run immediately without needing further instructions. But now you can use clearTimeout
to stop it:
clear.Timeout(myTimer);
How?
In the page animated modal the div is created in JS using document.createElement('div')
, innerHTML
and appendChild
. This is appended to document.body
as it has a CSS property of position: fixed
.
The function launchWarning()
is run when the page loads. The animation named grow
is in the CSS for the element and runs once when the element is created.
Another CSS animation called shrink
also runs but has animation-delay
set to 5 seconds. So the CSS could do all of this on it’s own (apart from the launch and close buttons) but the JS removes the element from the DOM just after the shrink
animation has played.
setInterval
This
Links
- Timing Events great article at Free Code Camp covering
setInterval()
,setTimeout()
,clearInterval()
andclearTimeout()
. - W3 Schools demo shows the code for
setTimeout()
with a way to pause in the middle. It’s a bit more complicated than you might expect.
-
A modal is a dialog box/popup window that is displayed on top of the current page. ↩︎