Is it beneficial to vary the time between function calls when utilizing setInterval in JavaScript?

My website is displaying two words one letter at a time, with a 0.1s delay between letters and a 3s pause after each full word. I attempted using setTimeout, but it's not functioning as expected. What could be the issue in my code?

var app = angular.module("app", []);

app.controller('mainCtrl', function ($scope) {
    var values = ['.com', 'available'];
    var index = 0;
    $scope.comval = '';
    function changeText (){
        if(values[index].length == $scope.comval.length) {
            $scope.comval = '';
            index++;
            if (index >= values.length) {
                index = 0;
            }
        }
        else
        {
            $scope.comval = values[index].substring(0, $scope.comval.length+1);
            $scope.$apply();
            console.log($scope.comval);
        }
    }

    setInterval(changeText,100);
});  

You can see this effect on another site by visiting this link. Look for the section shown in the image below:

https://i.sstatic.net/SPwGU.png

Check out the code snippet on JSFiddle.

Answer №1

To resolve this issue, I opted to utilize the setTimeout function (which calls the specified function once after a set time) instead of the setInterval function (which repeatedly calls the function). In order to ensure that the function is called multiple times, I nested the call to setTimeout within the function (changeText) so that it sets up a timer to call itself. This approach allows for flexibility in setting different delays for varying scenarios - 100 ms delay when printing a new letter and 3000 ms delay upon completing the printing of a new word.

var app = angular.module("app", []);

app.controller('mainCtrl', function ($scope) {
    var values = ['.com', 'available'];
    var index = 0;
    $scope.comval = '';
    
    function changeText() {
        if(values[index].length == $scope.comval.length) {
            $scope.comval = '';
            index++;
            
            if (index >= values.length) {
                index = 0;
            }
            
            // A full word has been printed!
            // Wait 3000 ms before calling the function again.
            setTimeout(changeText, 3000);
        } else {
            $scope.comval = values[index].substring(0, $scope.comval.length+1);
            $scope.$apply();
            console.log($scope.comval);
            
            // Only a single letter has been printed.
            // Wait 100 ms before calling the function again.
            setTimeout(changeText, 100);
        }
    }

    // Initiate the process.
    setTimeout(changeText, 100);
});

Fiddle.

Answer №2

To implement a time interval in your controller, you can utilize the $interval function as shown below:

$interval(changeText, 100);

Remember to include the $interval dependency in your controller.

UPDATE:

If you require a delay of three seconds before running the function, consider using the $timeout service like this:

$timeout(function() {
    $interval(changeText, 100)
}, 3000)

Once again, ensure that you inject $timeout into your controller.

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

When employing useEffect, clearInterval cannot halt the execution of SetInterval

My attempt to create a function that initiates a countdown when the isPlaying variable is true and stops when it's false has not been successful. Instead of working as intended, it starts multiple intervals concurrently. The value of isPlaying changes ...

Validation method in jQuery for a set of checkboxes with distinct identifiers

I am faced with a situation where I have a set of checkboxes that, due to the integration with another platform, must have individual names even though they are all interconnected. <div class="form-group col-xs-6 checkbox-group"> <label cla ...

Show a persistent header once you scroll past a certain point using Bootstrap

Utilizing Bootstrap affix property to reveal a header after scrolling down by 100px has been successful for me. However, I encountered an issue when trying to set the opacity property to 0.0001, it works as expected. But when setting it to 0 or changing di ...

Jest may come across test suites, but it discreetly disregards the individual tests

Having encountered an issue with Jest testing in a Nuxt/Vue v2 project, I found that after making some changes, the tests were no longer running. The unit tests were either passing or failing initially, but suddenly stopped running altogether. ----------|- ...

Ways to conceal components upon clicking a different element

Struggling to make this jQuery function properly. I have a form with all fields contained in a div.form-group. The subscribe button is identified by the id subscribe. I'm aiming to hide the form fields when clicked, but my JavaScript doesn't see ...

The dynamic data is not displaying on the Chart bundle JavaScript

I am currently utilizing chart bundle js for my project. While everything appears to be functioning properly on alter show, I am encountering an issue with the map display – nothing is showing up as intended. If anyone has a solution to resolve this iss ...

Struggling to display the array after adding a new item with the push method

Seeking assistance in JavaScript as a newcomer. I have written some code to print an array once a new item is added, but unfortunately, it's not displaying the array. I am puzzled as there are no errors showing up in the console either. In my code, I ...

Ways to simulate a constant that acts as a dependency for the service being examined?

I'm currently experimenting with a file named connect-key.js. It relies on a dependency called keyvault-emulator. Content of File #1: // connect-key.js file const { save, retrieve, init } = require('./keyvault-emulator') .... .... .... // ...

Click event not triggering on a div component in React

I'm having an issue with an onclick event on a div that is not triggering. <div className={styles.scrollingDiv}> <div className={styles.rectangleDiv} /> <div className={styles.menuBarDiv}> ...

What is the optimal method for iterating through every element in a string array?

Within my code, I am dealing with an array named var mya = ["someval1", "someotherval1", "someval2", "someval3"];. The goal is to have a function that receives an object with a property set to one of these values. Instead of simply iterating over the arra ...

I am attempting to incorporate an NPM package as a plugin in my Next.js application in order to prevent the occurrence of a "Module not found: Can't resolve 'child_process'" error

While I have developed nuxt apps in the past, I am new to next.js apps. In my current next.js project, I am encountering difficulties with implementing 'google-auth-library' within a component. Below is the code snippet for the troublesome compon ...

Incorporating additional information into the database

When I run the code, I see a table and a button. After entering data in the prompts as instructed, the table does not get updated. I'm unsure why this is happening. Can someone please explain? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Trans ...

Retrieving a Table Row from a TableView in Titanium Mobile

Does anyone know where the actual tableViewRows are stored within a TableView? When inspecting the TableView, I can see the headings for the Rows but not the Rows themselves. Can someone point me in the right direction to find where these Rows are contai ...

Using a single package manager for both backend and frontend development - is it possible? (Yarn/NPM)

Before, I relied on NPM for server-side tasks and Bower for frontend. NPM would install packages in the node_modules/ directory, while a .bowerrc file directed package installations to public/lib. Recently, I've made the switch to Yarn from NPM, and ...

Adding two headers to a post request in Angular 2 - a step-by-step guide!

Is there a way to combine 2 headers in the following code snippet: appendHeaders(json: PortfolioVO) { var newJson = JSON.stringify(json); var allHeaders = new Headers(); allHeaders.append('Content-type' , 'application/jso ...

When triggered by a click, the function gradually fades in and out. It superimposes one image on top of another, but unfortunately, the sizes

Due to different screen sizes, the image does not appear on top of another image exactly. It seems like a new function is needed. One that does not overlap with another image (by clicking the function for a few seconds), but rather replaces it for those fe ...

Is the use of addEventListener("load",... creating an excessive number of XmlHttpRequests?

Consider a scenario where you have the following JavaScript code running in a Firefox plugin, aimed to execute an XmlHttpRequest on a page load: function my_fun(){ var xmlHttpConnection = new XMLHttpRequest(); xmlHttpConnection.open('GET', ...

I aim to customize the options of a dropdown list based on the selection of another dropdown

I am looking for a way to dynamically filter employees based on the department selected. Unfortunately, my knowledge of JavaScript and Ajax is limited. <div class="pure-checkbox ml-15"> <input id="checkbox2" name="sta ...

Zone.js error: Promise rejection caught

When I call a function from an external library on page load in my Angular application, Chrome dev tools console shows the error message: "Unhandled Promise rejection: Cannot read properties of undefined (reading 'page') ' Zone: <root> ...

Check to see if a key exists within the entire JSON using jQuery

I'm struggling with checking if a specific key is contained in my JSON data array. I want to add a class or perform an action if the key is present, otherwise do something else. I've tried using inArray and hasOwnProperty but can't seem to g ...