<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by David Wenzel on Medium]]></title>
        <description><![CDATA[Stories by David Wenzel on Medium]]></description>
        <link>https://medium.com/@davidwenzel?source=rss-16fb26df85e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Lp8--xIUMLm8fSl1.png</url>
            <title>Stories by David Wenzel on Medium</title>
            <link>https://medium.com/@davidwenzel?source=rss-16fb26df85e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 12:16:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@davidwenzel/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[An Overview of Implementing Omniauth into a Ruby on Rails Application]]></title>
            <link>https://medium.com/@davidwenzel/an-overview-of-implementing-omniauth-into-a-ruby-on-rails-application-e56a97bf7aa6?source=rss-16fb26df85e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e56a97bf7aa6</guid>
            <dc:creator><![CDATA[David Wenzel]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 19:47:08 GMT</pubDate>
            <atom:updated>2023-04-23T21:01:53.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*LDizpJUnNeHpvw301N5PMw.jpeg" /></figure><p>As a software engineering student, I’ve been exploring the world of web application development, and I recently came across OmniAuth. It’s an incredibly powerful and flexible authentication system that allows users to authenticate with third-party services like Google, Facebook, and Twitter. Before diving into how to implement it in a Rails application, let’s first understand the process that takes place on Google’s side during authentication.</p><p>When a user clicks on the “Sign in with Google” button in an application using OmniAuth, they are redirected to Google’s authentication page. There, the user is prompted to grant the application access to their Google account. Google verifies the user’s identity and confirms that they grant the requested permissions. Once the user consents, Google generates an access token and an authorization code. The authorization code is sent to the callback URL specified in the Rails application.</p><p>Now that we understand the process a little better, let’s go through the steps to implement Google OmniAuth in a Rails backend web application. I also highly recommend you check out and review this github repo before you get started. it is a must.</p><p><a href="https://github.com/zquestz/omniauth-google-oauth2">-https://github.com/zquestz/omniauth-google-oauth2</a></p><ol><li>Register the application with Google and obtain the required API keys and credentials.</li><li>Configure the Rails application to use OmniAuth and the Google OAuth2 strategy.</li><li>Modify the SessionsController to handle the OmniAuth callback.</li><li>Create the necessary routes and views to support authentication.</li></ol><p>Step 1: Register the application with Google</p><p>First, you’ll need to register your application with the Google Developer Console. Create a new project, navigate to the “Credentials” section, and create new OAuth 2.0 client credentials. Make a note of the “Client ID” and “Client Secret” as they will be required in the next step.</p><p>Step 2: Configure the Rails application</p><p>Add the following gems to your Gemfile and run bundle install:</p><pre>gem &#39;omniauth&#39;<br>gem &#39;omniauth-google-oauth2&#39;</pre><p>Create an initializer file (e.g., config/initializers/omniauth.rb) and configure OmniAuth to use the Google OAuth2 strategy:</p><pre>Rails.application.config.middleware.use OmniAuth::Builder do<br>  provider :google_oauth2, ENV[&#39;GOOGLE_CLIENT_ID&#39;], ENV[&#39;GOOGLE_CLIENT_SECRET&#39;], skip_jwt: true<br>end</pre><p>Replace ENV[&#39;GOOGLE_CLIENT_ID&#39;] and ENV[&#39;GOOGLE_CLIENT_SECRET&#39;] with the appropriate values from the Google Developer Console.</p><p>Step 3: Modify the SessionsController</p><p>Now that OmniAuth is configured, we need to handle the OmniAuth callback in the SessionsController. Define an omniauth method that is called when the user is redirected back to the application after authenticating with Google. The method retrieves the authentication data from the request environment (request.env[&#39;omniauth.auth&#39;]), then finds or creates a user in the database using the provided email address. If a user is found or created successfully, a session is established, and the user is redirected to the appropriate page.</p><p>Step 4: Create routes and views</p><p>In config/routes.rb, add the following route:</p><pre>get &#39;/auth/:provider/callback&#39;, to: &#39;sessions#omniauth&#39;</pre><p>This will direct the callback from Google to the omniauth method in the SessionsController. You will also need to create a view with a &quot;Sign in with Google&quot; button or link that directs users to /auth/google_oauth2. This will initiate the authentication process with Google.</p><p>In summary, implementing Google OmniAuth in a Rails backend web application involves understanding the authentication process from Google’s perspective, registering the application with Google, configuring the Rails application to use OmniAuth, modifying the SessionsController to handle the callback, and creating the necessary routes and views. This process simplifies user authentication and offers a more streamlined user experience. As a software engineering student, I find this approach to be quite fascinating, as it allows us to leverage the power of existing authentication systems like Google’s and provide users with an easier and more convenient way to access our applications.</p><p>Going back to the information provided by Google during the authentication process, here is a brief overview of the data we receive:</p><ul><li>uid: A unique identifier for the user in Google&#39;s system.</li><li>info: A hash containing basic user profile information, such as name, email, and profile image URL.</li><li>credentials: A hash containing the access token and its expiration time.</li><li>extra: A hash containing additional raw data from Google, including the user&#39;s full profile information and the ID token.</li></ul><p>In our example, the omniauth method in the SessionsController extracts the user&#39;s email address from the info hash:</p><pre>auth = request.env[&#39;omniauth.auth&#39;]<br>user = User.find_or_create_by(username: auth[&#39;info&#39;][&#39;email&#39;]) do |u|<br>  u.username = auth[&#39;info&#39;][&#39;email&#39;]<br>  u.password = SecureRandom.hex # Generate a random password for the user<br>end</pre><p>Using the email address as the username ensures that each user has a unique identifier. You could also choose to store additional information from the info or extra hashes, such as the user&#39;s full name or profile picture, depending on your application&#39;s requirements.</p><p>Once the user is found or created in the database, the omniauth method establishes a session for the user and redirects them to the appropriate page in the frontend. If the user could not be logged in, they are redirected back to the login page.</p><p>As a software engineering student, implementing Google OmniAuth in a Rails backend web application provides valuable hands-on experience with web authentication and third-party integrations. By leveraging the power of established authentication systems like Google’s, we can create more user-friendly applications while also learning about the intricacies of web authentication and the OAuth 2.0 protocol.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e56a97bf7aa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Role of the Session Hash in User Sign-in and Authentication for Ruby on Rails Web Applications]]></title>
            <link>https://medium.com/@davidwenzel/the-role-of-the-session-hash-in-user-sign-in-and-authentication-for-ruby-on-rails-web-applications-1a11682c95db?source=rss-16fb26df85e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a11682c95db</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[coding-bootcamp-students]]></category>
            <dc:creator><![CDATA[David Wenzel]]></dc:creator>
            <pubDate>Mon, 20 Mar 2023 23:08:41 GMT</pubDate>
            <atom:updated>2023-03-20T23:12:48.363Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J90HWheufYCTYz-S" /><figcaption>Photo by <a href="https://unsplash.com/@joshuafuller?utm_source=medium&amp;utm_medium=referral">Joshua Fuller</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In web applications, user sign-in and authentication are essential components for managing access to resources and personalizing the user experience. The Ruby on Rails (RoR) framework provides a built-in mechanism for managing user sessions, which includes the use of session hashes. This post will delve into the role of the session hash in a Ruby on Rails web application, specifically for user sign-in and authentication.</p><p><strong>Understanding Sessions in Ruby on Rails</strong></p><p>A session in Ruby on Rails is a way to store data for a user between multiple requests. It allows developers to maintain a persistent state for users as they interact with different web application components. Sessions are beneficial for managing user sign-in and authentication, ensuring that only authorized users can access protected resources.</p><p>When a user signs in to a Rails application, their authentication information is stored in a session. This session data is then available throughout the user’s interaction with the web application, allowing developers to implement features like persistent login.</p><p><strong>Session Hashes in Rails</strong></p><p>In Ruby on Rails, sessions are implemented using a session hash — a data structure that maps keys to values. The session hash is stored on the server side and is associated with a unique session ID that is sent to the client’s browser as a cookie. The session ID is then used to retrieve the corresponding session data from the server-side storage when needed.</p><p>The session hash in Rails provides a secure and efficient way to store authentication data, such as the user ID, email, and other relevant information. By default, Rails encrypts and signs the session data to ensure its integrity and confidentiality. This means that malicious users cannot tamper with or eavesdrop on the session data, thus preserving the security of user authentication.</p><p><strong>Managing User Sign-in with Session Hashes</strong></p><p>When a user signs in to a Ruby on Rails web application, the authentication process usually involves checking the user’s credentials (e.g., email and password) against a database. If the credentials are valid, the user is considered authenticated, and their user ID or other identifying information is stored in the session hash. Here is an example of a session create and destroy method in a rails and react web app I recently made.</p><pre>class SessionsController &lt; ApplicationController<br>    skip_before_action :authorize<br><br>    def create<br>        user = User.find_by(username: params[:username])<br>        if user&amp;.authenticate(params[:password])<br>            session[:user_id] = user.id<br>            render json: user, status: :created<br>        else<br>            render json: { errors: [&quot;Invalid username or password&quot;] }, status: :unauthorized<br>        end<br>    end<br><br>end</pre><p>create action: This action is responsible for authenticating a user when they attempt to log in. It first finds the user object based on the provided username (using User.find_by(username: params[:username])). If the user exists and the provided password is valid (checked with user&amp;.authenticate(params[:password])), the user&#39;s ID is stored in the session hash (session[:user_id] = user.id). The user object is then rendered as a JSON response with a :created status. If the authentication fails, an error message is rendered as a JSON response with a:unauthorized status.</p><p><strong>Implementing Authentication Persistence with Session Hashes</strong></p><p>Once a user is signed in, the session hash allows Rails applications to maintain their authentication state across multiple requests. This is often referred to as “authentication persistence.”</p><p>Developers can use the data stored in the session hash to implement authentication checks throughout the application. For instance, a common pattern is to define a helper method, such as current_user, in the application controller. This method retrieves the user object based on the user ID stored in the session hash. Here is an example of an application controller file:</p><pre>class ApplicationController &lt; ActionController::API<br>  include ActionController::Cookies<br><br>  rescue_from ActiveRecord::RecordInvalid, with: :render_unprocessable_entity_response<br><br>  before_action :authorize<br><br>  def current_user<br>    @current_user ||= session[:user_id] &amp;&amp;<br>    User.find_by(id: session[:user_id])<br>  end<br><br>  private <br>  <br>  def authorize<br>    current_user<br>    return render json: { errors: [&quot;Not authorized&quot;] }, status: :unauthorized unless session.include? :user_id<br>  end<br><br>  def render_unprocessable_entity_response(exception)<br>    render json: { errors: exception.record.errors.full_messages }, status: :unprocessable_entity<br>  end<br><br>end</pre><p><strong>Implementing Access Control with Session Hashes</strong></p><p>The require_authentication method can then be used as a before_action filter in controllers to protect specific actions:</p><pre>class DashboardController &lt; ApplicationController<br>  before_action :require_authentication<br><br>  def show<br>    # ...<br>  end<br>end</pre><p>In this example, the require_authentication filter ensures that only authenticated users can access the show action in the DashboardController.</p><p><strong>Managing User Sign-out with Session Hashes</strong></p><p>Signing a user out of a Rails application is typically achieved by deleting the user’s authentication data from the session hash. For instance, a destroy action in the sessions controller can be used to sign a user out:</p><pre>class SessionsController &lt; ApplicationController<br>    skip_before_action :authorize<br><br>    ...<br><br>    def destroy<br>        session.delete :user_id<br>        head :no_content<br>    end<br><br>end</pre><p>In this code snippet, the session.delete(:user_id) method removes the user ID from the session hash, effectively signing the user out. The user is then redirected to the application&#39;s root page with a success message.</p><p>In Ruby on Rails web applications, the session hash plays a crucial role in managing user sign-in and authentication. It allows developers to store authentication data securely and efficiently, implement authentication persistence, enforce access control, and manage user sign-out. By leveraging the built-in session management capabilities of Rails, developers can create secure and user-friendly web applications that protect sensitive resources and provide personalized experiences.</p><p>Now you may be wondering how a session hash differs from a param hash as they are both used very often within a ruby on rails application.</p><h3><strong>Params Hash vs. Session Hash in Ruby on Rails Web Applications</strong></h3><p>In Ruby on Rails web applications, both the params hash and the session hash are essential data structures for managing user interactions and data flow. While they may seem similar at first glance, they serve distinct purposes and have unique characteristics.</p><p><strong>Params Hash</strong></p><p>The params hash in Rails is a data structure that holds user-supplied data received from HTTP requests (e.g., GET or POST). It stores parameters sent by the client, such as form data, query string parameters, or URL segments. Developers can access the values in the params hash in their controller actions to process user input or implement business logic.</p><p>For example, when a user submits a login form, the email and password entered by the user are stored in the params hash. The controller action responsible for authentication can then access these values to check the user’s credentials.</p><p><strong>Session Hash</strong></p><p>As discussed earlier, the session hash in Rails is a data structure used to store data persistently between multiple requests. It is primarily used for managing user sessions, authentication, and access control. The session hash is stored on the server side and is associated with a unique session ID, which is sent to the client as a cookie.</p><p>While the params hash is used for passing data between the client and the server during a single request, the session hash is designed to maintain state across multiple requests, making it ideal for storing data related to user authentication and access control.</p><p>The params hash and session hash in Rails serve different purposes. The params hash is used for capturing user input and passing data between the client and the server during a single request, while the session hash is used for maintaining user state and authentication data across multiple requests. Understanding the distinct roles and characteristics of these hashes is crucial for developing efficient and secure web applications in Ruby on Rails.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a11682c95db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby attr_reader, attr_writer and attr_accessor; differences, use-cases and examples]]></title>
            <link>https://medium.com/@davidwenzel/ruby-attr-reader-attr-writer-and-attr-accessor-differences-use-cases-and-examples-9853be3179f2?source=rss-16fb26df85e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/9853be3179f2</guid>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[David Wenzel]]></dc:creator>
            <pubDate>Sat, 17 Dec 2022 20:28:12 GMT</pubDate>
            <atom:updated>2022-12-18T17:58:05.332Z</atom:updated>
            <content:encoded><![CDATA[<p>Ruby provides several methods that allow you to create getter and setter methods for instance variables. These methods, attr_reader, attr_writer, and attr_accessor, are provided by the Module class, which is the class from which all modules are derived.</p><p>attr_reader and attr_writer are methods provided by Ruby&#39;s Module class, allowing you to create getter and setter methods for instance variables, respectively. You would use attr_reader if you only want to be able to read the value of an instance variable, and attr_writer if you want to write to the value of an instance variable.</p><p>On the other hand, attr_accessor is a method that creates both a getter and a setter method for an instance variable. It is a convenient way to create both methods with a single line of code, rather than having to use both attr_reader and attr_writer.</p><p>You might want to use attr_reader or attr_writer over attr_accessor in certain cases where you only need one of the methods and don&#39;t want to allow both reading and writing of the instance variable. For example, you might use attr_reader if you want to make an instance variable immutable (i.e., it cannot be changed after it is initialized), or you might use attr_writer if you want to allow the value of the instance variable to be changed, but don&#39;t need to read its value.</p><p>It is also worth noting that using attr_reader or attr_writer can be more efficient than using attr_accessor because they only create a single method, rather than two methods. However, in most cases, the performance difference is negligible, so you should choose the method that makes the most sense for your use case. It is worth noting that performance discrepancies are negligible between these methods, but does exist. However it may be more appropriate to choose which method you will use based on how the data will be manipulated, if at all after instantiation.</p><p>Here is a more detailed explanation of attr_reader, attr_writer, and attr_accessor, along with some examples of how they can be used in Ruby classes:</p><h3><strong>attr_reader</strong></h3><p>attr_reader is a method that creates a getter method for an instance variable. It allows you to read the value of the instance variable from outside the class, but not write to it. Here is an example of how attr_reader can be used:</p><pre>class Person<br>  attr_reader :name<br><br>  def initialize(name)<br>    @name = name<br>  end<br>end<br><br>person = Person.new(&quot;John&quot;)<br>puts person.name # &quot;John&quot;<br>person.name = &quot;Jane&quot; # Error: NoMethodError: undefined method `name=&#39; for #&lt;Person:0x00007fbbb8b12f38&gt;</pre><p>In this example, the Person class has a name instance variable, which is made readable using attr_reader. This allows you to access the value of name using the name method, as shown in the puts statement. However, if you try to write to name using the name= method, you will get a NoMethodError because the setter method was not created.</p><h3><strong>attr_writer</strong></h3><p>attr_writer is a method that creates a setter method for an instance variable. It allows you to write to the value of the instance variable from outside the class, but not read it. Here is an example of how attr_writer can be used:</p><pre>class Person<br>  attr_writer :name<br><br>  def initialize(name)<br>    @name = name<br>  end<br>end<br><br>person = Person.new(&quot;John&quot;)<br>person.name = &quot;Jane&quot;<br>puts person.name # Error: NoMethodError: undefined method `name&#39; for #&lt;Person:0x00007fa82391ebe0&gt;</pre><p>In this example, the Person class has a name instance variable, which is made writable using attr_writer. This allows you to change the value of name using the name= method, as shown in the person.name = &quot;Jane&quot; statement. However, if you try to read the value of name using the name method, you will get a NoMethodError because the getter method was not created.</p><h3><strong>attr_accessor</strong></h3><p>attr_accessor is a method that creates both a getter and a setter method for an instance variable. It allows you to both read and write to the value of the instance variable from outside the class. Here is an example of how attr_accessor can be used:</p><pre>class Person<br>  attr_accessor :name<br><br>  def initialize(name)<br>    @name = name<br>  end<br>end<br><br>person = Person.new(&quot;John&quot;)<br>puts person.name # &quot;John&quot;<br>person.name = &quot;Jane&quot;<br>puts person.name # &quot;Jane&quot;</pre><p>In this example, the Person class has a name instance variable, which is made readable and writable using attr_accessor. This allows you to both access and change the value of name using the name and name= methods, as shown in the puts and person.name = &quot;Jane&quot; statements.</p><p>Depending on the situation, you might want to use attr_reader, attr_writer, or attr_accessor depending on your needs. For example, you might use attr_reader if you only want to be able to read the value of an instance variable, or attr_writer if you only want to be able to write to the value of an instance variable. attr_accessor is a convenient way to create both a getter and a setter method with a single line of code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9853be3179f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fetch requests; differences in .then and async/await]]></title>
            <link>https://medium.com/@davidwenzel/fetch-requests-differences-in-then-and-async-await-824ebf081547?source=rss-16fb26df85e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/824ebf081547</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[David Wenzel]]></dc:creator>
            <pubDate>Sun, 18 Sep 2022 23:53:52 GMT</pubDate>
            <atom:updated>2022-09-18T23:53:52.278Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fetch requests; differences in .then and async/await</h3><p>Asynchronous code in javascript can be confusing, tricky, and hard to wrap your head around. However, async code makes our programs much more efficient, usable, and modern webpages simply rely on it! As developers understanding and implementing async code is a touchstone of our learning. One of the most common bits of async code used is a fetch() method. The fetch method is a javascript method used to fetch resources asynchronously across networks. For most beginning projects you will fetch information from a database and display it on the page. Making this method slightly trickier to implement in your program is due to the fact there are many ways to go about it. You have encountered multiple ways of completing this task in researching solutions for your goals. Two of the most popular ways to go about responding to the promise returned by fetch() are the .then and async/await syntactical responses. In this article, I will detail not only how to convert a syntactical .then expression into an async/await expression, but also some finer points on which situations these methods will be appropriate.</p><p>First, we need to understand this code’s ultimate goal. From a 10,000ft view; They respond to a resolved promise object which is returned from the fetch method. Depending on how the promise is resolved we will then take that object and run a series of further methods on it based on our goals. This article will stick to one of the most common fetch use cases. which is to fetch data from an API and display this data on our webpage.</p><p>The most common way to learn how to go about this task of responding to the resolved promise of the fetch is to use the .then methodology. Let’s take a look ;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*xlWbHpKtFhJrU7C9QGjzEg.png" /></figure><p>Within this block of code, we can see we are taking the resolved promise object and then running some methods on the received data to convert it into a more usable format for us to manipulate. .then can be explained as “when this promise is resolved THEN do this bit of code.” Commonly after one or two .then’ we will then see a .catch this is to respond to a promise which has been resolved as an error.</p><p>This method of performing a fetch method works just fine, however, there is a more modern and tidier way to do it. Let’s take a look and then we will break it down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qLmmhIUZxHdwxd0uX41jIw.png" /></figure><p>First and foremost we can see the entire function is wrapped in async, that is designating the following code is asynchronous and is required by javascript for it to compile correctly.</p><p>In this section of code, we can see we are assigning a variable with the keyword await. This portion after await will be assigned to the variable AFTER the async promise is resolved! We chain these items together in that same single-threaded fashion we are used to in javascript!</p><p>There are many reasons other than simply using a more modern syntax for doing it this way.</p><p>One — async/await syntax reads more like synchronous code and is easier to follow</p><p>Two — async/await is great for code that needs to execute sequentially which is common in a fetch request. We cannot move on until one preceding step is resolved.</p><p>Three — .then may be more efficient when displaying a loading symbol or code that needs to act parallel or while the rest of the promise is being resolved.</p><p>Now you might be asking — how do we catch if the promise resolves in error? That is a great question. Take a look;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qLmmhIUZxHdwxd0uX41jIw.png" /></figure><p>This is called a try-catch. If At any point during the execution of the try block there is an error javascript will jump to the catch block of code. The catch block accepts one parameter; an error and allows you to perform your desired response on said error.</p><p>To wrap all this up; on my journey I often encountered this syntax and become intimidated and confused, but after the slightest bit of review and reflection, I discovered that the async/await syntax is cleaner, and easier to read, but also has a caveat in that it cannot run blocks in parallel so in some instances it may be better to use our trusty .then syntax.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=824ebf081547" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Stopwatch in JavaScript]]></title>
            <link>https://medium.com/@davidwenzel/how-to-create-a-stopwatch-in-javascript-d8085f9d0cd4?source=rss-16fb26df85e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8085f9d0cd4</guid>
            <category><![CDATA[programing]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding-bootcamp-students]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[David Wenzel]]></dc:creator>
            <pubDate>Thu, 28 Apr 2022 00:01:56 GMT</pubDate>
            <atom:updated>2022-04-28T00:01:56.579Z</atom:updated>
            <content:encoded><![CDATA[<p>How to Create a Stopwatch in JavaScript</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WieuPqDMCbXvKgyvqpY_eg.png" /></figure><p>Stopwatches have many uses! Integrating a stopwatch into your webpage can increase functionality and in some cases provide a better experience for your users! In this post I will explain how to program a stopwatch with ‘Start’, ‘Stop’, and ‘End’, buttons! There are many ways to create a stopwatch in Javascript so I encourage you to explore and share any alternative methods please feel free to share improvements to this method! This post does not go over HTML, styling, or how to display this onto the DOM, depending on your particular project.</p><p>The first step in creating a stopwatch is to initialize the variables we will be using to run the javascript logic and display the result to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*LoRaoWHHwH03-D9AkoKLyw.png" /></figure><p>We also need to initialize a variable titled ‘interval’ and set it to ‘null’ as well. This creates a title for our timer functionality which we will be running the setInterval() method on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*Qm7n5stUOfTIGBS8E5LsnA.png" /></figure><p>The main logic of the stopwatch will be held in one function. We will define this function as startTimer. Luckily, the way setInterval and clearInterval work we only need to create a function for when the stopwatch will be doing the only thing that is set to do…which is COUNT UP! We use a series of incrimination for this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*Gxy6PmQa0n6l17Krl4Y7-A.png" /></figure><p>As the code snippet shows we increment the seconds variable and using if statements we then increment the next unit of measure for the stopwatch every time the seconds variable is divisible by sixty a single time. We then reset the variable which has reached 60 to 0. To reiterate step by step;</p><p>-we increment our seconds variable</p><p>-our if statement checks to see if our seconds are strictly equal to 1 after divided by 60 (hence it is 60 seconds or 60 minutes)</p><p>-if our if statement comes back as true we set our unit of measure to 0 and increment the next unit of measure.</p><p>-we repeat for minutes into hours</p><p>While this is great and works, to keep our stopwatch visually appealing and consistent with common stopwatches (iOS, Android, etc..) we will want to arrange our stopwatch digits into a 00:00:00 format. To do this we use the toString method and if else statements to concatenate a ‘0’ onto the front of our variable (if they are only one digit or less than 10) after we parse our variable toString to keep our data of the same type. That looks like this;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*7JgbRvHvknl9CEXHptgeCw.png" /></figure><p>Great! Now our code has all pertinent variables, our function increments those variables in the correct order and we have the logic to arrange them in a visually appealing way! Our next step is to fire our function on a one-second interval. To do this we use the setInterval method.</p><p>setInterval takes two arguments. The first is the function it will fire and the second is the interval or tempo it will fire on. The setInterval() method fires a function on a set interval which we define as the 2nd parameter of the method in milliseconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*aUOffewiRMb-4R3LswjM7A.png" /></figure><p>As you can see we are using the interval variable which we initialized at the beginning of our code as a global variable and are reassigning it from null to our method which we pass in our startTimer function as the first argument and 1000 milliseconds as our second argument. When we use an event listener to fire off our call back our set timer function will fire off every second. That will look something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0chXQRAGEgEM5dKYAhXpeg.png" /></figure><p>As you can see, we are using an event listener on a button to fire our startTimer function to which we apply the setInterval method. In addition, we are using a series of if else statements to set and switch our button inner text, which is again used in our statements to determine if the stopwatch needs to run or stop running, which we control by setting or clearing our interval. clearInterval works simply by passing the name of the interval as an argument to it. In our case, that name is ‘interval.’</p><p>There we have it! Depending on your particular application the options are limitless for tweaks and improvements, but I hope I’ve provided the general framework and beginning logic for you to build out your stopwatch!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8085f9d0cd4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>