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

What is the best way to pass a CSS root constant to a separate CSS file?

In my Angular test project, I'm experimenting with using the same colors repeatedly. To achieve this, I created a constants.css file where I defined all my root constants, which currently consist of colors. However, I've hit a roadblock when atte ...

Retrieve the current URL of an IFRAME

How can I easily retrieve the current URL from an embedded iframe? The user will be navigating through various web pages. I assume that some JavaScript code would be needed for this task. ...

What is the best way to integrate Halfmoon's JS from npm into my current code using Gulp?

I am eager to incorporate the Halfmoon framework into a personal project and have successfully downloaded it through npm. To utilize the example JavaScript provided on this page (found at ), I need to import the library using a require statement. var halfm ...

Show the current temperature data retrieved from the weather API

I'm trying to figure out what's causing the issue with the temperature not displaying. Can anyone help me identify and fix the error? <script type="text/javascript"> $.ajax({ url: 'https://api.weather.gov/gridpoints/EWX ...

Guide on sending a JSON object to an EJS javascript loop efficiently

Seeking assistance with passing a Json object named myVar to the home.ejs file below. How should I assign the value to the variable called data? <table id="example" class="table table-striped table-bordered dataTable" cellspacing="0" width="100%"> ...

Disable body scrolling on mobile devices in native browsers

When using the native browser on Samsung Galaxy S5 / S6, the following CSS code: body { overflow: hidden; } does not successfully prevent the body from scrolling. Is there a way to work around this issue? Edit: As mentioned below, one workaround is t ...

Can you please guide me on retrieving information from an API using HTML, CSS, and JavaScript?

My task is to develop a web application using HTML, CSS, and JS with the following functionality: Retrieve a list of users from this API: https://jsonplaceholder.typicode.com/users. Upon clicking on a user, show a list of albums associated with that user ...

Style your content using PHP and CSS to format text with multiple selectors

My HTML code looks like this: <div id="main"> <aside class="readableCenterAside left"> ## Content 1 ## </aside> <aside class="readableCenterAside right"> ## Content 2 ## </aside> </div> Here is my CSS: .readableCe ...

The reload/refresh feature for images is not functional

When generating images automatically, I noticed that the file with the same name gets updated but is not reflected in the browser. $("#image_test").attr("src", data) I have tried: d = new Date(); $("#image_test").attr("src", data+d.getTime()); , $("#i ...

JavaScript - combining elements of an array of time

I've encountered a challenge where I need to calculate the total time duration from an array that contains time durations like ['00:30', '01:30', '03:00', '04:30']. The code snippet I'm using for this task ...

Differences in behavior of multiple select with track by in Angular versions above 1.4.x

I recently upgraded my product from Angular 1.2.x to 1.4.x. Since updating to angularjs 1.4.x, I've encountered an issue: What I have: I included code snippets for both angular 1.2.0 and 1.4.8. You can check out the comparison on JSFIDDLE. Explanat ...

The background color of the columns is overwhelming

I would like to create a TV remote control design using bootstrap, but I am encountering some issues. The background color is overflowing and I'm unsure how to fix it. Please take a look at the code and feel free to offer any suggestions! @media scre ...

Selecting the quartile value for every individual data point

I am currently graphing the sentiment values of tweets over a span of 10 years. The CSV file contains three columns as outlined below. Successfully, I managed to plot each value by date. However, upon attempting to create an area graph, I encountered an i ...

Achieve full height for the span tag within a div using CSS styling

I am facing a particular scenario: In a bootstrap row with 2 columns: - the first column contains a table with a button to add new rows - the second column has a label and a span (although it doesn't have to be a span) Both columns have equal hei ...

I can't seem to figure out the source of this unexpected padding/margin on my website

After creating a website for a church using Foundation, SASS, and Compass, I noticed a horizontal scroll issue when resizing the window. Adding overflow-x: hidden; seemed to fix it, but there was still about 20px of padding on the right side when testing ...

Tips for altering promises within nested for loops?

Presented below is a complex function that aims to extract model variants from a csv file, which are stored as strings in an array. The path of this csv file depends on information obtained from other csv files, hence the need for looping. The csvService. ...

the integration of shapes in three.js is malfunctioning

There has been a dynamic change in the path. The previous render function was as follows (where LENGTH, getPosition(), RADIUS, MATERIAL, and SCENE have already been set) var prevPosition = getPosition(); for(var i =0; i < LENGTH; i++) { drawPath(g ...

How to handle non-ASCII characters when encoding in JSON?

I understand that json_encode requires UTF-8 encoding, and I have already ensured that my data is encoded as such. However, when attempting to pass a PHP array to JavaScript, I am encountering difficulties in transferring the data successfully. To test th ...

Removing all repetitions from an array in JavaScript

My collection of objects includes the following inputs: var jsonArray1 = [{id:'1',name:'John'},{id:'2',name:'Smith'},{id:'3',name:'Adam'},{id:'1',name:'John'}] There is a dupl ...

Expanding the size of your Bootstrap 3 input box

Incorporating Bootstrap 3 into a Flask application, I have created a basic layout so far: <div class="container"> <div class="row"> <div class="col-xs-12"> <div class="content"> <div class="pull-middle"> ...