What is the reason that the setInterval function does not function properly when the value function is stored in a

Can someone assist with a JavaScript issue I am facing? I tried using a function in a variable for a typing effect and passed the variable into setInterval method, but it didn't work. However, when I placed the same function directly inside setInterval, it worked perfectly. Any idea why this happened?

var button = document.getElementById('mybutton');
        var mytext="thequickredfoxjumpsoverthelazybrowndog";
        //var i=0;
        //var typewriter = null;

        // first code function in var 
        var x = function() {
        
            document.getElementById('type')
              .textContent += mytext[i];
          
            i = i + 1;
          
            if (i > 20) {
          
              clearInterval(typewriter);
            }
        };
        
        
        mybutton.onclick = function() {
          'user strict';
        
          typewriter = setInterval(x, 10);
        };
<input type="button" id="mybutton">
        <div id="type"></div>

var button = document.getElementById('mybutton');
        var mytext="thequickredfoxjumpsoverthelazybrowndog";
        var i=0;
        var typewriter = null;

        // second  code function directly in setInterval

        mybutton.onclick = function() {
          'user strict';
        
          var typewriter = setInterval(function() {
        
        
            document.getElementById('type')
              .textContent += mytext[i];
        
            i = i + 1;
        
            if (i > 20) {
        
              clearInterval(typewriter);
            }
          }, 10);
        
        
        };
<input type="button" id="mybutton">
        <div id="type"></div>

Answer №1

Make sure to properly initialize variable i within the window scope of your JavaScript code for it to work correctly.

Please ensure that variable typewriter is also initialized within the window scope rather than inside a function scope as you currently have it.

var button = document.getElementById('mybutton');
var mytext="thequickredfoxjumpsoverthelazybrowndog";
var i=0;
var typewriter = null;

// Ensure that the first code function is defined properly
var x = function() {


  document.getElementById('type')
    .textContent += mytext[i];

  i = i + 1;

  if (i > 20) {

    clearInterval(typewriter);
  }
};


mybutton.onclick = function() {
  'use strict';

  // Set the interval for typewriter effect
  typewriter = setInterval(x, 10);
};
<input type="button" id="mybutton">
<div id="type"></div>

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

Generate Random Quotes - Each new quote should be different from the previous one

As I tackle the FreeCodeCamp 'Random Quote Machine' front end library project using React JSX, everything seemed to be running smoothly except for one major issue - the same quote was often generated two or three times in a row. Obviously, this i ...

The webpage displays the element as <span class="icon">&#xe80d;</span> instead of rendering it properly

In my ReactJS project, I have created a component called Menu1item: class Menu1item extends React.Component{ render(){ return ( <div> {this.props.glyph}{this.props.value} </div> ) ...

Modifying the Redux state using an array with prototypes

In my React application, I am utilizing Redux along with the ChartJS library to create charts. Occasionally, when I extract an array from the global Redux state, it appears in this format: ejeY: Array(7) 0: 43783 1: 85001 2: 100960 3: 752 ...

Amcharts displays individual balloons for each graph instead of a single balloon for all graphs

My goal is to have a single balloon for all stacked graphs. I modified my code according to this guide. Unfortunately, the data for messages is not being displayed. https://i.sstatic.net/2MRhc.jpg Did I make an error in my implementation? function creat ...

Is it possible to reload the webpage just one time after the form is submitted?

Can anyone suggest how I can refresh the webpage using PHP after submitting a form? I've been searching for a solution but haven't found one yet. Your assistance would be greatly appreciated. ...

Unable to insert a JSON object into an array using JavaScript and MongoDB

I'm encountering an issue when trying to push data into my Student model with the following schema: var StudentSchema = new Schema({ firstName: { type: String, trim: true, default: '' //validate: [validat ...

Using Firebase Admin or the regular Firebase with Next.js

Currently, I am working on a project using Next.js and integrating Firebase. I have been successfully fetching data in my components using the Firebase package designed for frontend use. However, I recently attempted to utilize Firebase within getServerS ...

In my JavaScript code for generating a Fibonacci series, I aim to include a comma at the end of each string

I am currently working on a JavaScript program to generate a Fibonacci series, and there are certain conditions that need to be met: Each number in the series should be separated by a comma. The method should handle invalid values and return -1 for integ ...

What is the best way to collapse additional submenus and perform a search within a menu?

Whenever a sub-menu is activated, only the current sub-menu should be open while the others remain closed. I need the search function to be enabled on the text box and display all items containing the specified value while also changing the color of <a ...

What are the steps to integrate the vue-tweet-embed node package into vuejs2?

I am having trouble figuring out how to implement the vue-tweet-embed plugin in my Vue file. I keep getting an error message that says: Unknown custom element: - have you properly registered the component? If dealing with recursive components, ensure ...

I encountered an issue while attempting to utilize a JavaScript script - I received an error message stating "Uncaught ReferenceError: jQuery is not defined."

Currently, I am utilizing a template with multiple pages and I need to use one of them. I followed all the necessary steps correctly, but I encountered an error in the console that says Uncaught ReferenceError: jQuery is not defined. Below is my HTML scrip ...

Even with React.memo(), functional components continue to trigger re-renders

I am facing an issue with my button component that contains a button inside it. The button has a state isActive and a click function passed to it. Upon clicking the button, the isActive flag changes, triggering the app to fetch data accordingly. However, t ...

Is there a way to transform my drag-and-drop function into a click event instead?

I am currently contemplating a modification to my drag and drop game. The game involves a grid of words, with the highlighted word to be spelled. Traditionally, players would drag and drop letters to complete the word. However, I am now exploring the idea ...

Having trouble activating the Invalidate Cache function in rtk query with tags

Here is a snippet from my Api.js file: export const api = createApi({ reducerPath: 'api', baseQuery: fetchBaseQuery({ prepareHeaders: (headers, { getState }) => { const userInfo=JSON.parse(localStorage.getItem('userInfo' ...

The rule 'react-hooks/exhaustive-deps' does not have a defined definition

I received an eslint error message after inserting // eslint-disable-next-line react-hooks/exhaustive-deps into my code. 8:14 error Rule 'react-hooks/exhaustive-deps' definition not found I tried to resolve this issue by referring to this p ...

What is a memory-saving method to clear an object in JavaScript?

I am looking for a way to use the same object repeatedly in JavaScript by emptying it after its purpose is served, without creating a new object each time. In arrays, I usually do arr.length=0 to clear an array instead of assigning it to a new memory locat ...

Can you explain the distinction between firstChild and childNodes[1]?

Exploring the distinction between child nodes and child elements within JavaScript DOM: For instance, var myTbodyElement = myTableElement.firstChild; versus var mySecondTrElement = myTbodyElement.childNodes[1]; Is it possible to interchangeably use firs ...

Tips for dynamically loading images in React with a Collage component

It appears that all the examples I've come across are static in terms of loading images. While the code works, it does not display the divider <div> tag as expected. Instead, the results (images) are shown stacked in the first item of the Collag ...

Accessing JSON data in Node.js

I'm completely new to working with Node.js and I've been trying to figure out the best way to parse and query a JSON object. Recently, I came across this JSON object that I have loaded as a file: [ {"Key":"Accept","Values":["Application/x-www-fo ...

Firefox detects video interference from webcam

Take a look at this test code: <!doctype html> <html> <body> <video id="v1" autoplay="autoplay"></video> <script> navigator._getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserM ...