How to harness the power of loops in JavaScript

Having trouble getting this code to repeat a CSS transition properly.

        for (var i=0 ; i<4 ; i++){ 
       setTimeout(function() {
        $('#top-left').css('margin', '45px 0 0 45px');
        $('#top-mid').css('margin', '45px 0 0 90px');   
        $('#top-right').css('margin', '45px 0 0 135px');
        $('#mid-right').css('margin', '90px 0 0 135px'); 
        $('#bot-right').css('margin', '135px 0 0 135px');
        $('#bot-mid').css('margin', '135px 0 0 90px');
        $('#bot-left').css('margin', '135px 0 0 45px');
        $('#mid-left').css('margin', '90px 0 0 45px');            
    }, 4500);  

        setTimeout(function() {
        $('#top-left').css('margin', '180px 0 0 180px');
        $('#top-mid').css('margin', '180px 0 0 90px');  
        $('#top-right').css('margin', '180px 0 0 0');
        $('#mid-right').css('margin', '90px 0 0 0');
        $('#bot-right').css('margin', '0 0 0 0');
        $('#bot-mid').css('margin', '0 90px 0 90px');
        $('#bot-left').css('margin', '0 180px 0 180px');
        $('#mid-left').css('margin', '90px 0 0 180px');             
    }, 9000);

    };

http://jsfiddle.net/hamidrezabstn/JCE7t/1/

Answer №1

If you want to implement a timer in JavaScript, you can consider using the setInterval() function. First, initialize a variable like var count = 0;. Then, use the setInterval() method to check the value of this variable and apply CSS modifications accordingly.

An example implementation could look like this:

var interval;
var count = 0;

function startTimer() {
    interval = setInterval(updateCount, 4500);
}

function updateCount() {
    count++;
    // Apply CSS modifications here

    if (count === 4) {
        clearInterval(interval);
    }
}

For more examples and information, you can refer to this StackOverflow thread on using setInterval and clearInterval.


Additional Note:

I quickly put together a demonstration which you can view on this fiddle link:

var interval4500;
var interval9000;
var count4500 = 0;
var count9000 = 0;

$(function () {
    $('#top-left').click(function () {
        $(this).css('margin', '0 0 0 0');
        $('#top-mid').css('margin', '0 90px 0 90px');
        $('#top-right').css('margin', '0 180px 0 180px');
        $('#mid-right').css('margin', '90px 0 0 180px');
        $('#bot-right').css('margin', '180px 0 0 180px');
        $('#bot-mid').css('margin', '180px 0 0 90px');
        $('#bot-left').css('margin', '180px 0 0 0');
        $('#mid-left').css('margin', '90px 0 0 0');
    });
    interval4500 = setInterval(updateCount4500, 4500);
    interval9000 = setInterval(updateCount9000, 9000);
});

function updateCount4500() {
    count4500++;
    // Apply CSS modifications at 4500ms intervals

    if (count4500 === 4) {
        clearInterval(interval4500);
    }
}

function updateCount9000() {
    count9000++;
    // Apply CSS modifications at 9000ms intervals

    if (count9000 === 4) {
        clearInterval(interval9000);
    }
}

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

Ways to choose an option from a drop-down menu without the select tag using Selenium

I'm looking to perform automated testing with Selenium using Java but I'm facing an issue when trying to select an item from a dropdown list. The HTML structure does not include a select tag for the drop-down menu items (such as Auth ID and Corre ...

What effect does setting AutoPostBack to "true" in an ASP dropdownlist have on the fireEvent() function?

I am currently working on an aspx page. This page includes three dropdown lists and a button, all of which are populated dynamically based on the code written in the code-behind file (.cs file). To achieve this, I need to utilize two event handler methods ...

Transferring specific form data through a POST request

I am attempting to transfer specific values from a form to PayPal once the form is submitted. Below is the code for my form: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form class="form-horizo ...

In the XHTML mode, MathOverflow's invaluable mathematical expertise shines brightly

I am interested in incorporating the unique “piece of valuable flair™” from MathOverflow onto my website. The issue I am facing is that I want my webpage to comply with XHTML5 standards, meaning it should be served with the MIME type application/xht ...

Exploring the Possibilities of HTML5 Data- Attributes with Select2 4.0

Here is how I have defined my select element: <select class="myselect"> <option value="AL" data-foo="bar">Alabama</option> ... <option value="WY" data-foo="biz">Wyoming</option> </select> In the previous versi ...

There seems to be an issue with the location.href function in the server-side code of

I'm encountering an issue in the code below where I am attempting to redirect to the login page, but it seems to not be functioning as expected. app.get('/current-pass', (req, res) => { res.sendFile(path.join(staticPath, "currentPass ...

The combination of a modal box, checkbox, and cookie feature creates

I am trying to accomplish the following tasks: When the homepage loads, I want a modal box to appear Inside the modal box, there should be a form with a mandatory checkbox After checking the checkbox, submit the form and close the modal box to return to ...

The issue of not displaying results in a DIV when using CakePHP 2 and jQuery

I'm having trouble creating an auto-refreshing DIV with updated data. Despite everything appearing to be correct, it's not displaying any results on the webpage. Any assistance would be greatly appreciated :) Controller: public function homeNe ...

Exploring date range options in Highcharts for viewing data from a specific selected date

Using HTML, JS, and Controller public function graph(Request $request) { $statistics = DiraStatistics::where('date_access',$request->date)->get(); $question_asked_sum = $statistics->sum('question_asked'); $low_ ...

It is not possible to recycle a TinyMCE editor that is embedded in a popup

Having a frustrating issue with the TinyMCE Editor plugin embedded within a Fancybox pop-up window. I have a list of objects with Edit links that trigger an AJAX call to retrieve content from the server and place it in a <textarea>. A TinyMCE editor ...

Utilize the cached version of jQuery if it has been recently updated, otherwise proceed with downloading the newest

Is it possible to optimize loading time for certain users by selecting a specific version of jQuery? Identify a suitable version x of jQuery, such as x = 1.4.1, and determine if the user has a more recent version y of jQuery cached. If so: if (y > x = ...

Step-by-step guide on showcasing AJAX outcome within a table row

I am facing an issue with my AJAX process while trying to display the current value inserted in a new row of a table after successfully adding it to the database. I am unable to figure out how to echo or display the values. Immediate assistance is needed t ...

Is it possible to execute a command in the terminal that is related to the package.json file?

Objective Create a program to analyze user engagement data for a hypothetical menu planning calendar app. The program should be able to track the activity of users based on their meal planning within the app. Data Overview In the ./data folder, there ...

Creating an inclusive h1 header with a logo: A step-by-step guide

Is there a way to have a logo linked to the homepage and also have an h1 element that is invisible? This is my current layout: <header id="pageHeader"> <h1> <a href="<?php bloginfo('url'); ?>"> & ...

I am unable to send back my JSON object

I seem to be having trouble returning a JSON object as all I get is an undefined variable. The code below is supposed to fetch a JSON element from an API. It appears to work within the success: function, but when attempting to use that data elsewhere, it ...

Webpack resolve.alias is not properly identified by Typescript

In the Webpack configuration, I have set up the following: usersAlias: path.resolve(__dirname, '../src/pages/users'), In my tsconfig.json, you can find: "baseUrl": ".", "paths": { "usersAlias/*": ["src/pages/users/*"], } This is how the cod ...

Passing arguments from an Angular directive to a controller function within an element's HTML

Is there a way to pass the URL of an anchor tag in the directive to the controller function "itemClicked"? The code below successfully logs the "post" object when clicked. HTML: <div ng-repeat="post in posts" > <div find-urls link-clicked="i ...

Automating user login with node.js and passport.js: A step-by-step guide

My login application is built using node.js and passport.js, with the session being maintained using express-session and connect-mongo. I need to ensure that users are redirected to the home page upon accessing the URL, only sending them to the login page ...

Extracting Query Parameters from a Successful Ajax Call in Javascript

How can I extract data from the success response? Take a look at my code snippet: $.ajax({ async: 'true', url: 'https://exampleapi.com/product', type: 'GET', data: {page: idQuery}, success:(response => { v ...

What is the best way to track all method calls in a node.js application without cluttering the code with debug statements

How can I automatically log the user_id and method name of every method called within a javascript class without adding logger statements to each method? This would allow me to easily track and grep for individual user activity like in the example below: ...