The Art of Typewriter Magic

Why is the output of the first code block just 'T' repeated, whereas the second block of code works as expected?

function typeWriter() {
  var i = 0,
  txt = 'Testing',
  speed = 40,
  typed = document.getElementById('typewriter');

  (function addChar() {
    if (i < txt.length) {
      typed.innerHTML += txt.charAt(i);
      i++;
      setTimeout(typeWriter, speed);
    }
  })();
} 

document.onload = typeWriter();

Second code block:

var i = 0,
  txt = 'Testing',
  speed = 40;

function typeWriter() {
  if (i < txt.length) {
    document.getElementById('typewriter').innerHTML += txt.charAt(i);
    i++;
    setTimeout(typeWriter, speed);
  }
}

Answer №1

The initial code block ensures that every invocation of typeWriter() initializes i to 0, resulting in consistently returning 'T'. On the other hand, in the subsequent instance, i is declared external to typeWriter(), allowing its value to remain unchanged across multiple invocations.

Answer №2

When attempting to repeatedly call the typeWriter() function until i >= txt.length, it is essential to avoid resetting the value of i every time the function is called. To achieve this, defining i outside the function as shown in the 2nd block is necessary for the desired outcome.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I need to update my database by sending requests to my API, as the changes are not being reflected in the current database state. I am eager to see the

Struggling to grasp the concept of making requests to an API that uses express for CRUD operations. In the code snippet below, .get(/bears) displays a form and in app.post('/bears'), I'm using the 'request' module to send a request ...

Start flicker issue in Vue 3 transition

I have created a carousel of divs that slide in and out of view on the screen. However, I am facing an issue where during the start of each transition, when a new div is rendered (i.e., the value of carousel_2 changes), it appears without the transition-en ...

Having trouble locating a method in $scope following angular $compile

Apologies for the simple question, I am a beginner in AngularJS and front-end development. I am attempting to create a modal using bootbox as shown below: In Service: function _modalData(){ let element = "<div onclick=\"saveSelecti ...

Effortlessly refresh a data object in Vue.js without relying on a function

I need assistance with the following: <Checkbox label="View" :initialState="data.something" @updateStatus="updateCheckbox" > </Checkbox> The variable data.something is a b ...

What was Douglas Crockford trying to convey with the term 'created in an alternate window or frame'?

What did Douglas Crockford mean when he mentioned that the is_array() test might not correctly identify arrays created in a different window or frame? var is_array = function (value) { return value && typeof value === 'object&apos ...

How can I use Jquery to loop through each combobox on the page and delete those with a specific class name?

I am currently dealing with a page that contains multiple combo-boxes. Each combo-box has a default option set as empty, which is given the class name 'hide'. This functionality seems to work perfectly in Chrome and Firefox, as the hidden options ...

What is the best way to retrieve an element from an array within a script?

As a newbie in the realm of vue and Laravel Framework, I am eager to fetch data from an API and display it dynamically on my web page. To achieve this, I have already set up a table named 'Progress' where I seeded some initial data. Utilizing AP ...

What is the best way to extract a value from a string using JavaScript?

In my string labeled as 'content', I have the phrase "data-RowKey=xxx" embedded within it. I attempted to extract the 'xxx' portion using the code snippet below: var val = content.substring(12 + content.indexOf("data-RowKey="), 3); Un ...

Is there a way to retrieve the groups of match/matchAll similar to accessing an array?

My goal is to convert a version string to a number using the following code: function convertVersionToNumber(line) { const groups = line.matchAll(/^# ([0-9]).([0-9][0-9]).([0-9][0-9])\s*/g); return parseInt(groups[1] + groups[2] + groups[3]) ...

Having trouble installing gatsby-plugin-transition-link using npm

https://i.stack.imgur.com/DyZxQ.png I'm facing some issues while trying to install gatsby-plugin-transition-link using npm. No matter what solutions I've attempted, the errors persist. Can anyone provide insight into what might be causing this p ...

Investigating Javascript memory usage in Internet Explorer 6

Our application is experiencing severe performance issues in IE6 due to its heavy reliance on JavaScript and the majority of activity taking place within a single page. In this browser, we are noticing that memory continues to accumulate without being cle ...

Prevent page refresh when submitting a form using PureCSS while still keeping form validation intact

I'm currently implementing PureCSS forms into my web application and facing a challenge with maintaining the stylish form validation while preventing the page from reloading. I discovered that I can prevent the page reload by using onsubmit="return f ...

Vuetify's scrolling list feature allows for smooth navigation through a list

Check out my Vuetify code snippet that utilizes a list: <v-list> <v-list-tile v-for="user in users" :key="user.id" avatar @click="" > <v-list-tile-content> < ...

Buttoned Up: The Troubling Tale of jQuery and

Seems like this question might be a duplicate, but I'm not bothered. Despite searching on Google, I haven't found a solution. What could be the mistake here? $(document).ready(function() { $("#foo").click(function() { $.ajax({ type ...

In Angular JS, the event count for ng-model is consistently set to 11

After creating a sample of all the Angular Js events, I noticed that when the page is initially loaded, the default value of the model textbox is always showing as 11. I am curious to understand why this default value is set to 11. Here is an excerpt from ...

Executing several Javascript functions when the page is loaded

I have attempted to invoke 4 JavaScript functions from the HTML body when the page is loaded. Each function calls a JSP servlet to retrieve data from a database and populate the respective list boxes. Currently, I am focusing on the edit screen where I am ...

JavaScript not redirecting to HTML page as expected

I have developed a basic login page that makes an Ajax request to the backend. However, I am experiencing difficulties with redirecting the page upon successful login. The redirect function only seems to work 1 in 15 times, and I'm unsure of the reaso ...

Incorporate audio playback on image click using JavaScript, with the feature to automatically pause the playback if multiple images are playing simultaneously

<img class="cl" src="photo/198.jpg"/></br> <audio class="cs" controls> <source src="audio/198 banu nagamothu.mp3" type="audio/mpeg"> </audio> I prefer not to have audio controls initially, but when the image i ...

Modifying the CSS display property in Javascript following a media query update

Seeking a solution for a table that needs to be visible on desktop but hidden on mobile, with the option of clicking a button to toggle its visibility. Currently, the javascript function close_table() sets display:none which overrides the CSS display:block ...

The browser sends a request for a file, the server then downloads a pdf, and finally, the

Here is the process I am trying to achieve: 1) A browser sends an ajax request to the server, requesting a pdf file. 2) The server downloads the pdf file and returns it for display. 3) The browser then displays the downloaded pdf in an existing iframe. Be ...