The setInterval function in Javascript seems to be malfunctioning

I've been working on this code that should display a tree made up of random symbols. I implemented setInterval to change the symbols every second, but for some reason, it's not working and I'm not getting any error messages. Could someone please point out where I might have gone wrong or offer some advice? :)

window.onload = intervalSetup;
function intervalSetup() {
'use strict';
setInterval(function() {
theTree();
}, 1000);
}

function theTree() {
'use strict';
var x = 8;
for (var i=0; i<x; i++) {
for (var j=x-1; j>i; j--) {
document.write("&nbsp;&nbsp;");
}
for (var k=0; k<=(i*2); k++) {
document.write(arraySigns[Math.floor(Math.random() * arraySigns.length)]);
}
document.write("<br>")
}
for (var i=0; i<2; i++) {
for (var j=0; j<(x*2)-3; j++) {
document.write("&nbsp;");
}
document.write("**<br>");
}
}

Answer №1

After running some tests on Google Chrome, the code performed as expected.

The only issue encountered was an undefined error in the arraySigns.

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

Answer №2

By writing to the document, the script successfully removed itself. This prevented the function from being called more than once.

Quite a humorous bug, don't you think? :-)

Answer №3

One issue that arose was an array that was undefined, but this was resolved through editing.

The main problem encountered was the continuous writing of trees on the page, making it difficult to observe changing symbols.

To remedy this, a solution was implemented where the tree is generated within a container div that is cleared before the creation of each new tree. This ensured that the symbols appeared random with each iteration.

A functional example provided in the code snippet involves updating the innerHTML of the treeDiv at specific intervals. The document fragment was omitted for clarity purposes.

'use strict';
window.onload = intervalSetup;
var arraySigns;
var treeDiv;

function intervalSetup() {  
  arraySigns = ["*", "^", "&", "#"];
  treeDiv = document.getElementById("theTreeDiv");
  setInterval(theTree, 1000);
}

function theTree() {
  treeDiv.innerHTML = '';
  var x = 8;
  
  for (var i=0; i<x; i++) {
    
    for (var j=x-1; j>i; j--) {           
      treeDiv.innerHTML += "&nbsp;&nbsp;";
    }
    
    for (var k=0; k<=(i*2); k++) {      
      treeDiv.innerHTML += arraySigns[Math.floor(Math.random() * arraySigns.length)];
    }
    treeDiv.innerHTML += "<br>";  
  }
  
  for (var i=0; i<2; i++) {
    
    for (var j=0; j<(x*2)-3; j++) {
      treeDiv.innerHTML += "&nbsp;";
    }   
    treeDiv.innerHTML += "**<br>";
  }
}
<div id="theTreeDiv">
  
</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

Determine if an object is already present in a JSON array by comparing their respective IDs

I have a shopping cart stored in JSON format. [{"tuote":{"id":"2","name":"Rengas 2","count":16,"price":"120.00"}},{"tuote":{"id":"1","name":"Rengas 6","count":"4","price":"25.00"}},{"tuote":{"id":"4","name":"Rengas 4","count":"4","price":"85.00"}}] Form ...

Exploring Nested Collections with KnockoutJs in an Asp.net MVC Environment

I have the following .net class: public class JobDetailsDTO { public string JobName { get; set; } public string CompanyName { get; set; } public String[] IndustryName; } I am trying to connect this to a Knockout JS model, but my nested collec ...

Dealing with a jQuery/JavaScript issue involving thumbnail images

I am facing an issue with smooth transitions between thumbnail images in HTML list tags. I have Jquery listeners set up for mouseenter and mouseleave events that update a parent image when a thumbnail is hovered over. The problem arises when scrolling fro ...

A guide to extracting functions from a `v-for` loop in a table

Beginner here. I am attempting to create a dropdown menu for the div with an id matching my specific name. For instance, let's say my table column names are: A, B, C. I only want to have a dropdown menu for column A. The template of my table looks ...

When using $.ajax, special characters are not rendered properly, displaying strange symbols instead of accents such as "é" or "ã"

I'm struggling to display the letter "é" using $.ajax and a JSON file. I've tried setting everything up with <meta charset="utf-8"> but all I get is an alert window showing "". Any help is appreciated, just not looking for PHP solutions. H ...

Adding incremental values to a variable using JavaScript within the framework of jQuery and AJAX

In my JavaScript code that utilizes jQuery and AJAX, I have created a dynamic array containing multiple values for AJAX requests. The array is structured as follows: <script type="text/javascript> var array = Array("y", "y", "x", "y", "y", "y"); fu ...

An issue in Node.js NPM PDFkit arises when generating PDF tables with Voilab pdf table, leading to paragraph errors in the resulting

Greetings everyone, I appreciate you taking the time to visit. I am currently facing some challenges with Voilab PDF Kit, a library for PDFkit that is designed to assist in organizing tables for NPM Pdfkit. After successfully generating a table, I attemp ...

Learn how to successfully carry on with event.preventdefault in JavaScript

Is there a way to create a modal that prompts the user to confirm if they want to leave the page without committing changes? These changes are not made within a <form> element, but rather on a specific object. I've attempted to use both $route ...

The EventListener functions properly only when the browser window is not in focus

In my Angular application, I am using Two.js to draw an SVG image. After drawing the SVG with some elements in Two.js, I add event listeners to its elements like so: this.courtRenderer.update(); // once this command is executed, Two.js will draw the SVG f ...

Retrieve the variable from a function that is invoking the export.modules in node.js

How can I extract the code from the randomCode() function in the users.js file, assign it to the result variable, and use it throughout the entire '/login' endpoint? randomCode.js const crypto = require('crypto') const randomCode = (c ...

The recursion in the Lodash function has gone beyond the stack size limit

The objective I have set out to develop a unique "deepMapValues" function. This function is designed to take a specified function and an object, apply the function to each value in the object deeply, and return the modified object accordingly. (v, k) => ...

Retrieve information from an external JSON file and display it in a jstree

I am trying to pass JSON data to a jstree object from an external file. The code snippet I have does not seem to be working properly. <script> $.jstree.defaults.core.themes.responsive = true; $('#frmt').jstree({ plugins: [" ...

issue with integrating promise in angular 4

I'm currently learning about promises and how to implement them in Angular. I have written the following code in StackBlitz. My goal is to display the array whenever it contains a value by using promises in Angular. This is my HTML code: <h2>A ...

Navigating the AngularJS Directive Controller

I am encountering difficulties while trying to access my controller within a directive that I am attempting to unit test using jasmine and karma testrunner. The structure of the directive is as follows: directive angular.module('Common.accountSearch ...

I would like to implement a delay on this button so that when it is clicked, there is a pause before navigating

When I add the delay, it doesn't work, and when I remove it, it does. What can I do to make this button have a href link that delays before redirecting to another page? (I'm a newbie) I need to click and wait 3 seconds before navigating to other ...

Tips for Automatically Loading Dependencies in AngularJS

Currently, I am working on an Angular application where I am designing various widgets using HTML5. Here is a snippet of the code structure: <html ng-app> <div ng-controller="widget1"> </div> <div ng-controller="widget2"> ...

Component fails to update when attribute is modified

My issue is that the crud-table component does not refresh when I change currentTable. It works when I assign currentTable = 'doctor' in the created() hook, but not here. Why is that? <template> <div id="adminpanel"> <div id ...

From declaring variables locally to accessing them globally in JavaScript

I'm facing an issue with JavaScript, webRTC, and Kurento that I can't seem to resolve on my own. My problem arises when trying to store the remote stream from a local variable into a global variable. I'll explain the steps leading to the iss ...

Verify for redundant entries in the database when the button is clicked

I have a specific requirement that involves verifying whether the user is repeatedly inputting the same Project and Survey No. An alert should be triggered if the same combination is entered twice upon button click. Below is the HTML code snippet: <t ...

Tips for resolving the error code 'ERR_REQUIRE_ESM' when working with code: to correct this issue, make sure to include the necessary library using the 'require' statement in the correct

How can I resolve this issue? I am working on an App chat project. Apologies if my language is hard to understand, as I am Thai. PS C:\Users\ADMIN\Desktop\chat\server> node server.js C:\Users\ADMIN\Desktop\ch ...