Executing a function a specific number of times in Jquery

I have a query regarding JQuery related to randomly placing divs on a webpage. The issue I'm facing is that it currently does this indefinitely.

Is there a way to make it run for a specific duration and then stop?


$(document).ready(function () {
  makeDiv();

var count = 1;
function makeDiv() {

count ++;
while (count < 50){
var numRand = Math.floor(Math.random() * 501);
var divsize = 100;
var posx = (Math.random() * ($('body').width() - divsize)).toFixed();
var posy = (Math.random() * ($('body').height() - divsize)).toFixed();
$newdiv = $("<div class='exploding'></div>").css({
'left': posx + 'px',
'top': posy + 'px'
});
$newdiv.appendTo('body').delay(2000).fadeIn(100, function () {
//$(this).remove();
makeDiv();
});
}
}
});


body, html {
width: 960;
height: 100%;
}
div.box {
position: relative;
width: 100px;
height: 100px;
}
div.exploding {
position: absolute;
width: 10px;
height: 10px;
background-color: red;
}

Answer №1

To enhance the efficiency of the code, it is recommended to declare the count variable inside the makeDiv function instead of globally. Additionally, include count++ at the end of the while loop to increment its value. Avoid calling the same makeDiv() function within the while loop as it may cause overload.

$(document).ready(function () {
  makeDiv();


  function makeDiv() {
    var  count = 1;
  
    while (count < 50){
      var numRand = Math.floor(Math.random() * 501);
      var divsize = 100;
      var posx = (Math.random() * ($('body').width() - divsize)).toFixed();
      var posy = (Math.random() * ($('body').height() - divsize)).toFixed();
      $newdiv = $("<div class='exploding'></div>").css({
        'left': posx + 'px',
        'top': posy + 'px'
      });
      $newdiv.appendTo('body').delay(2000).fadeIn(100, function () {
        $(this).remove();
      });
        count ++;
    }
  }
});
body, html {
    width: 960;
    height: 100%;
}
div.box {
    position: relative;
    width: 100px;
    height: 100px;
}
div.exploding {
    position: absolute;
    width: 10px;
    height: 10px;
    background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №2

In order for the increment to work correctly, count++; must be placed within the while loop

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

Break apart PDFs into individual images or convert to HTML

I'm currently working on a project that requires the development of a unique webtool. The purpose of this tool is to allow users to effortlessly upload their PDF documents, which will then be displayed in a browser with an engaging page flip effect ut ...

Click and release file upload

I am working on creating a drag and drop upload feature where the user can drop files onto a div, and then click an upload button to send them to the server. I'm facing an issue with JavaScript not recognizing the variable fd. How can I pass that vari ...

Transferring data between two functions within a React.js application

I have two functions called getLocation() and getLocationName(). The getLocation() function performs an XMLHttpRequest, and I want to pass the response to the getLocationName() function to display it in a list. getLocationName = (location) => { var ...

Can Vuex mapActions be utilized within a module that is exported?

Is it possible to utilize Vuex mapActions from an external module imported into a component? I am working on standardizing a set of functions in a vue.js web application. My goal is to import these functions into each component and pass necessary values f ...

Steps to create a stunning parallax effect using Greensock

Accomplishment After discovering a captivating parallax animation on the hero video of Antoni.de, I was intrigued by two specific elements. Firstly, the smooth scrolling effect and secondly, the mesmerizing parallax effect incorporated within the header v ...

Refresh the div by clicking it

$(window).load(function() { $("#Button").click(function() { alert('clicked') $("#div").load(" #div > *"); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script ...

Discover the process of creating a dynamic mailto link using AJAX and HTML

One of my tasks involves extracting email addresses from an XML document using AJAX, and then displaying them on a webpage as clickable links for sending emails. Here is a snippet of JavaScript code I am working with: emailobj = listings[i].getElementsBy ...

What is the best way to halt the current event handler thread's execution when another event is triggered that calls the same handler at

One of the functions in my code filters and sorts contents of a select dropdown based on input text entered by the user. The function filterSort() is triggered on each keyup event from the input field. Code $(inputTextField).keyup(function() { / ...

Is the callback of $.post not being executed until the loop it's contained in finishes?

I'm working on a stock table that allows users to input the quantity of stock to issue. I have a function that verifies whether or not the database has sufficient stock for each entry in the table. When debugging through the code in Chrome, I noticed ...

How to Route in Angular 5 and Pass a String as a Parameter in the URL

I am currently working on an Angular project that focuses on geographic system data. The concept is as follows: I have a component with the route: {path: 'home'}. I aim to pass a geojson URL along with this route, making it look like this: {pat ...

Guide to simulating Twilio with Jest and TypeScript to perform unit testing

Please assist me in mocking a Twilio service that sends messages using Jest to mock the service. Below is the code I am working with: import { SQSEvent } from "aws-lambda"; import { GetSecretValueResponse } from "aws-sdk/clients/secretsmanag ...

Storing JSON response data in jQuery cache according to the endpoint

I am currently working on a way to cache a JSON response in case the endpoint fails or takes too long to respond to the request. From a previous Stackoverflow question, I have come up with this function. However, there is an issue where the function alway ...

Having difficulty executing the command 'npm install -g expo-cli'

When attempting to execute npm install - g expo-cli on a Windows 10 machine, I am encountering issues. An error message keeps popping up and preventing me from proceeding. I'm in desperate need of assistance! npm WARN deprecated <a href="/cdn-cgi/ ...

Having trouble getting a NodeJS sample app to start up because it can't locate the 'config' file?

I am currently delving into the world of Node.js and have been attempting to launch a sample application that I recently acquired from a git repository: https://github.com/madhums/node-express-mongoose-demo Despite diligently following all the provided i ...

Having trouble displaying information in a table using React JS

I devised a feature to display one column of a table and one column for checkboxes (each row should have a checkbox). I stored this file in a component folder with the intention of creating a page where the user selects an account type, and then a new tabl ...

Trouble with Sound during Quickblox Webrtc Audio Calls

I am having an issue with my audio calls. When I make a call to another user, everything seems fine except that I cannot hear any sound when speaking into the microphone. I am only interested in making audio calls. The call is initiated by pressing a butt ...

How can strings of dates be arranged in MM/DD/YYYY order?

Is there a correct way to sort these dates in descending order? I've attempted using arr.sort() and arr.sort().reverse(), searched extensively on stack overflow, but still cannot find a solution. Every attempt at sorting them seems to be incorrect. [ ...

Trigger a function following a collection update in Angular Meteor

I am in the process of developing a multiplayer game, and I would like a specific function to be triggered once the first player updates an "isStarted" field in the collection. Within my controller code: angular.module('mcitygame').directive(&a ...

What are the best practices for managing live notifications with WebSocket technology?

I have developed a real-time chat application in React.js with Socket.io, but I want to implement a new feature. Currently, User A and User B can only communicate if they both have the chat open. I would like to notify User B with a popup/notification wh ...

JSON is often portrayed as a singular value

I am attempting to save settings in my SQL Database and then restore them using ajax and php. However, I am encountering an issue where only one long JSON Value is returned instead of three separate values for each setting. Settings: {"setting1":"true","se ...