Skip to content

Instantly share code, notes, and snippets.

@usmaanalii
Created September 7, 2017 07:45
Show Gist options
  • Save usmaanalii/ced1689fcd8baceae9ee930796f34675 to your computer and use it in GitHub Desktop.
Save usmaanalii/ced1689fcd8baceae9ee930796f34675 to your computer and use it in GitHub Desktop.

What I learned on this mini-project.

setInterval() and clearInterval()

The setInterval method has been used in previous projects, but in this case it's used a little differently, in conjunction with clearInterval.

When you wish for a function or code piece of code to run every so often, setInterval can be used.

https://gist.github.com/f0fedc9697313a2480ce745ac1b4ce0b

Here, an anonymous function which defines a constant is ran every 1000 milliseconds.

In order to clear the countdown variable i.e stop the method running via setInterval you need to clear it. If you don't do this, and try to run the method whilst it's already running (through another function call), they will both run, which can cause erratic behavior.

https://gist.github.com/a2d19f22d687d1110cf3ca2c0c7a9b8b

Here, the method being executed under a given time interval is assigned to countdown, so clearing the variable does the job of cancelling the method calls.

Working with timestamps

If you want the current time, then Date.now() can be used, this will return the number of milliseconds elapsed since 01/01/1970.

It's easy to turn this into a date object via new Date(milliseconds), where the value extracted from Date.now() is used as a parameter.

Using this object, various methods can be called, to extract different aspects of the time data such as the day, month and year.

https://gist.github.com/2edab3f3864ddcdc74de90ce26554692

Form element selectors

When you want to attach an event to a form, you can utilise this to extract it's input values.

https://gist.github.com/2ab90d1bd1f8196d973a347e271c23e5

Here, an event listener is attached to the form via its name attribute customForm, and its inputs are extracted by accessing properties off this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment