What could be the reason for the delay in the JavaScript number generator?

I have limited knowledge of Javascript, so I modified this code by forking a Pen. Despite searching for similar posts, none seemed to address the issue with lag that I am experiencing. The delay occurs even when there is only one number displayed, making me question if the second script is contributing to the problem. I aim to consistently display the first number after 1 second and the second number after 2 seconds.

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

app.controller('MyRngCtrl', function($scope, $timeout) {
  $scope.rngESUS = 0;
  (function update() {
    $timeout(update, 1000 * 1);
    $scope.rngESUS = Math.round((Math.random() * 5) + 1);
  }());
});


app.controller('MyRngCtrl2', function($scope, $timeout) {
  $scope.rngESUS2 = 0;
  (function update() {
    $timeout(update, 1000 * 2);
    $scope.rngESUS2 = Math.round((Math.random() * 5) + 1);
  }());
});
.number {
  font-size: 25px;
  font-weight: 800;
  font-family: arial, sans-serif;
  text-align: center;
  color: red;
}

h4 {
  font-size: 20px;
  font-family: arial, sans-serif;
  text-align: center;
  margin: 1rem 0 0.5rem 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<body ng-app="myApp">

  <h4>ONE SECOND PUNCH</h4>
  <div class="number" ng-controller="MyRngCtrl">
    {{rngESUS}}
  </div>

  <h4>TWO SECOND PUNCH </h4>
  <div class="number" ng-controller="MyRngCtrl2">
    {{rngESUS2}}
  </div>

</body>

Answer №1

Why not utilize the $interval feature instead?

In addition, I've implemented a function called nextRand to guarantee that the subsequent random number differs from the previous one. This serves as a proof that the interval is functioning smoothly.

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

function randRange(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function nextRand(curr) {
  let next;
  do { next = randRange(1, 6); }
  while (next === curr);
  return next;
}

app.controller('MyRngCtrl', function($scope, $interval) {
  $scope.rngESUS = 0;
  $interval(function () {
    $scope.rngESUS = nextRand($scope.rngESUS);
  }, 1000);
});


app.controller('MyRngCtrl2', function($scope, $interval) {
  $scope.rngESUS2 = 0;
  $interval(function () {
    $scope.rngESUS2 = nextRand($scope.rngESUS2);
  }, 2000);
});
.number {
  font-size: 25px;
  font-weight: 800;
  font-family: arial, sans-serif;
  text-align: center;
  color: red;
}

h4 {
  font-size: 20px;
  font-family: arial, sans-serif;
  text-align: center;
  margin: 1rem 0 0.5rem 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<body ng-app="myApp">

  <h4>ONE SECOND PUNCH</h4>
  <div class="number" ng-controller="MyRngCtrl">
    {{rngESUS}}
  </div>

  <h4>TWO SECOND PUNCH </h4>
  <div class="number" ng-controller="MyRngCtrl2">
    {{rngESUS2}}
  </div>

</body>

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

Having difficulties linking the front end and the back end despite diligently following the tutorial

Currently, I am experimenting with creating a real-time chat application by following a tutorial on YouTube from JavaScriptMastery. The tutorial link is here, and the GitHub repository is available at this link. Despite closely mimicking the code displayed ...

What is the method for displaying HTML newlines in PHP?

Within a <textarea>, I input multiple numbers on separate lines by pressing enter. When I submit the form, these numbers are received on the server side as 'X'. However, when I echo 'X' to the browser, the numbers are separated by ...

jQuery/MVC3 script not triggering onclick event after initial execution

Hey there, I'm having an issue with a function that is triggered when clicking on an image. It seems to only be called once even though I expect it to be called multiple times. Here's the JavaScript code, combined with a bit of razor syntax, tha ...

Incorporating tags into the react-select component

https://i.sstatic.net/Fsknq.pngI am still a beginner in the world of react-js. Currently, I am experimenting with the following: https://i.sstatic.net/4Ggoz.png This is what I have attempted so far: const options = [ { value: 'chocolate', ...

Navigating through asynchronous functions without the use of promises

After delving into web-app development using angularJS with its promise library, I find myself facing a new project that lacks such a feature. How can I tackle this challenge without importing an external promise library? To simplify the situation, I need ...

Trouble with utilizing the dot operator to access JSON object with key from a string array in JavaScript

After receiving a JSON object from a PHP file using $.ajax(), I found that accessing the values was a bit tricky. For example, if my PHP file returned echo json_encode(array('a' => 'b')). When trying to access this data using the fo ...

Building connections in parse.com using various classes (JavaScript SDK)

Currently using parse.com in conjunction with the JavaScript SDK. Despite my extensive research, I have been unable to find any examples that directly address the issue I am facing. Here is the specific goal I am striving to accomplish: I aim to establi ...

In what situations is it appropriate to utilize the getInnerHtml() method?

Within Protractor, an ElementFinder instance has access to the getInnerHtml() method: var elm = element(by.id("myid")); expect(elm.getInnerHtml()).toEqual("test"); Interestingly, this method is not included in the official API list. Can you think of any ...

Discover the power of utilizing JavaScript to sort through table rows by filtering them based on the selections of multiple checkbox

How can I create interdependent logic for checkbox sections in a form to filter based on all selections? I am looking for help with my code snippet that showcases checkboxes controlling the visibility of table rows: $(document).ready(function() { $(" ...

"Encountering an issue where the route function in Passport and ExpressJS is not being

When using passport for admin authentication, I am facing an issue where the redirect is not calling my function. Consequently, all that gets printed on login is [object Object] Here is my code: app.get('/admin', isLoggedIn, Routes.admin); ...

Unsure if values can be imported from one component to another in Vue.js using props

Currently experimenting with Vue and ran into a minor challenge - wondering if there's a solution to this. I am looking to add a new value to my items array using my Button component so that I can display it using v-for. While consolidating everything ...

Is there a way to prevent text from overlapping a Material UI React Textfield when it is scrolled up and set to position sticky?

Scenario: In my chat application, I have the chat displayed in the middle of the screen with a sticky textfield at the bottom. My goal is to ensure that when users scroll through the chat messages, the textfield remains at the bottom but appears on top of ...

What is the reason behind the "request aborted" error occurring when using the express res.download() method?

I am encountering an issue with the following code snippet from a node.js server utilizing the express framework: var fs = require('fs') express = require('express') handlebars = require('express-handlebars'); var he ...

what is the method for passing query string parameters in an XMLHttpRequest to a PHP page

I have a PHP variable named $name=$_POST["name"]; <script> pge = '<?php echo $name ;?>'; var url = "searchCustomerByNameApi2.php" //some code xmlhttp.open("GET", url + "?pge=" + pge, true); xmlhttp ...

Using jquery to reveal a hidden element by smoothly fading it in

Is it possible to display a concealed div while simultaneously creating a fading effect in jQuery? ...

What is the reason for the global impact of CSS-Modules on html elements?

There is a file named mycomponent.module.css button { width: 10vw; min-width: 150px; } It seems like this CSS is being applied globally instead of just to the specific component where I imported it. Could it be that CSS modules only work on class ...

The initial time delay set by setTimeout does not seem to have any impact

The issue with setTimeout not working as expected lies in its execution order. The code below it gets executed without waiting for the delay specified in the first argument of 'setTimeout' to run. (function() { var a = ['#bird',&ap ...

Showing information using ng-repeat from a JSON collection

Here is the JSON data I am working with: $scope.track = [{ title: 'Group Therapy 150 with Above & Beyond and Maor Levi', date: new Date(), link: "https://www.mixcloud.com/widget/iframe/?embed_type=widget_standard& ...

Tips for resolving the problem when encountering the "undefined data" issue in the success callback of an AJAX request

I am facing an issue with my JSP page where I have a button that calls an Ajax method named "sendmail()" upon click. The send mail API is in the Controller, and I am trying to display an alert message in the Ajax success function using data.message, but it ...

React hook form submit not being triggered

import React, { useState } from "react"; import FileBase64 from "react-file-base64"; import { useDispatch } from "react-redux"; import { makeStyles } from "@material-ui/core/styles"; import { TextField, Select, Input ...