Set time out 5 seconds for one by one number in array, but not for all at once

settimeout javascript
setinterval javascript
javascript settimeout loop
clearinterval
javascript timer
settimeout vs setinterval
javascript setinterval stop
settimeout javascript mdn

I have array with 100 numbers, i want to add active class to 20 of them, that part is ok and working. But i want delay between every number.

I tried with settimeout, but it only delays for 5 seconds all numbers at once, but i want to set active class one by one with delay of 5 seconds. Please help.

function numbers() { 
                    
                        var activequantities;
                    activequantities = "@Html.DisplayFor(modelItem => item.Numbers)".split(",");
// this is array with sorted random numbers 20 of 100 example [22,33,46,57,etc]


                    function setClassNextItem(index)
{
    if (index >= activequantities.lenght) return;

    var value = activequantities[index];
    $(`.grid-container div[data-tabid=${value}]`).addClass('active');
    setTimeout(setClassNextItem(++index), 5000);
}

$(".grid-container div").removeClass('active');
                    setTimeout(setClassNextItem(0), 5000);

                        
                        
                }

Try to convert activequantities to a numbers array and do something like this:

function setClassNextItem(index)
{
    if (index >= activequantities.lenght) return;

    var value = activequantities[index];
    $(`.grid-container div[data-tabid=${value}]`).addClass('active');
    setTimeout(setClassNextItem(++index), 5000);
}

$(".grid-container div").removeClass('active');
setTimeout(setClassNextItem(0), 5000);

Scheduling: setTimeout and setInterval, setTimeout allows us to run a function once after the interval of time. These methods are not a part of JavaScript specification. For instance, this code calls sayHi() after one second: All arguments have the same meaning. seconds let timerId = setInterval ( ( ) => alert ( 'tick' ) , 2000 ) ; // after 5 seconds  All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time. To stop further calls, we should call clearInterval(timerId). The following example will show the message every 2 seconds. After 5 seconds, the output is stopped:

Iterate through your filtered elements array and add an (index + 1) * interval timeout for the callback to add the classname.

for (i = 0; i < 20; i++) {
  setTimeout(
    function (i) {
      //$this.addClass("active");
      console.log(`Add "active" class to element ${i}`);
    },
    (i + 1) * 1000, // shortened to 1 second for demo
    i
  );
}

Linux System Programming: Talking Directly to the Kernel and C Library, probably here because it is possible that data became available after the call n, is equal to the value of the highest-valued file descriptor in any set, plus one. If this parameter is not NULL, the call to select() will return after tv_sec seconds, and Thus, if the timeout was set for 5 seconds, and 3 seconds elapsed before a​  The window object allows execution of code at specified time intervals. These time intervals are called timing events. The two key methods to use with JavaScript are: setTimeout(function, milliseconds) Executes a function, after waiting a specified number of milliseconds. setInterval(function, milliseconds)

Welcome to stackoverflow! The function setTimeout returns an Async Promise that will resolve in x ms. If you run this function in a loop, you simply add more promises to be resolved, but they will all resolve close to the same time. Ex:

Send first Promise : it will wait 5 seconds One miliseconds later, send another promise that will wait 5 second ... 5 seconds later the first Promise resolve correctly. 1 ms later, the second promise resolve correctly ...

This behaviour makes all of your promises resolve almost at the same time, just 5 seconds after you initialized them.

In your case, since you want to execute a function at a precise interval, you need the setInterval. The setInterval function also takes a time in MS and a function but it repeat this function every x ms, or until the interval is stopped programmaticaly. EX:

var counting = 0;
var myInterval = setInterval(function() {
    //we do something...
    console.log('loop:' + counting ++);
    if(counting === 10) {
        // we do this 10 times, than we stop the interval
        clearInterval(myInterval);
    }
}, 1000);

Scientific American, For all the large telescopes it is the general practice to swing the tube about its The tube makes one complete revolution in twenty-four hours, and in order to give the verniers so as to read to 1,13 minute in declination and 5 seconds in time. This theorem, no doubt. grew out of failures of Fermat to find whole numbers  Note that the timeout is only triggered once, i.e. when timeout_trigger is called after 2 seconds it is not called again. To make it be continually called every two seconds you would need to add another call to setTimeout() at the end of the timeout_trigger function. This is covered in the final example of this post.

Drew's answer is the best and simplest so far. Another option is to go the async function/promise route.

/**
 * Time in milliseconds to wait between setting elements to active.
 */
const delayTime = 500, // shortened to half a second for the example
  $app = $('#app');

/**
 * Whether or not the routine is currently running.
 */
let stopped = true;

/**
 * Returns a promise that resolves after the specified number of milliseconds.
 */
function delay(ms) {
  return new Promise(res => setTimeout(res, ms));
}

function setActiveInSerial() {
  // a little user-friendly UI work
  stopped = !stopped;
  if (stopped) {
    $('#btn').text('Run');
  } else {
    $('#btn').text('Stop');
  }

  // promise that lets us serialize asynchronous functions
  let promise = Promise.resolve();

  $app.children().each(function() {
    promise = promise.then(async() => {
      if (stopped) {
        return;
      }

      $(this).addClass('active');

      // wait for `delayTime` to pass before resolving the promise
      await delay(delayTime);
      
      $(this).removeClass('active');
    })
  });
  
  // mark the routine as stopped and reset the button
  promise.then(() => {
    stopped = true;
    $('#btn').text('Run');
  });
}

// populate with items
for (let i = 1; i <= 20; i++) {
  $app.append($('<span>').text(`Item ${i}`));
}

// attach function to run button
$('#btn').click(setActiveInSerial);
#app {
  display: flex;
  flex-direction: column;
}

#app .active {
  background-color: cyan;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn">Run</button>
<div id="app"></div>

Methods and Tools of Parallel Programming Multicomputers: Second , To understand what is taking place in reality the following set of test computations was run by applying one processor, and at the same time different ways of the The two versions of programs were realized: in the first one the static arrays 3,0 2,5 2,5 64 1,2 1,0 1,6 64 1,2 0,9 1,0 In Table 1 the time is given in seconds  TIME Formula in Excel. Time is a time worksheet function in excel which is used to make time from the arguments provided by the user, the arguments are in the following format respectively hours, minutes and seconds, the range for the input for hours can be from 0-23 and for minutes it is 0-59 and similar for seconds and the method to use this function is as follows =Time( Hours, Minutes

Bulletin of Prosthetics Research, 19 No. 1) Spring 1982 The “page" represented in Figure 1 allows the user to. the video monitor, has access times of 10 to 20 seconds for any one of aids for the nonvocal handicapped person (1) which usually contain an array of and key words and is displayed in an alphanumeric read-out somewhere on the board. The second button changes the color into red, but after 10 sec. the 3rd button changes color to green and not the second one. The second button is red all the time, now the 3rd button works perfectly. I’m totally confuse. I have 38 buttons to set to work this way.

Arduino Internals, The bit patterns for the segments are stored in a const byte array called numerals​[]. Because It's constant data, and it's not going to change in the course of the sketch's execution. There's HIGH to turn off all the LEDs at once. Each time through the Timer/Counter 2 overflow interrupt, one digit is decoded and displayed. One detail of the datetime64 and timedelta64 objects is that they are built on a fundamental time unit. Because the datetime64 object is limited to 64-bit precision, the range of encodable times is $2^{64}$ times this fundamental unit. In other words, datetime64 imposes a trade-off between time resolution and maximum time span.

Cooperative asynchronous JavaScript: Timeouts and intervals , NOTE: The specified amount of time (or the delay) is not the guaranteed time counts from 1 to 10 billion, your callback will be executed after a few seconds. setTimeout() returns an identifier value that can be used to refer to the It then runs the function once per second using setInterval() , creating the  //one second after the first beep Beep! //one second after the second beep Time's up! //one second after the third beep The AnnoyingBeep program uses a three-argument version of the schedule method to specify that its task should execute once a second, beginning immediately. Here are all the Timer methods you can use to schedule repeated

Comments
  • Are you asking for a delay of 5 seconds between each successive element you added a class to? i.e. first => 5s, second => 10s, ... Nth => (N * 5)s?
  • i have updated my question
  • Same thing happens, it add active classs instantly to all numbers from array without delay between each number. I created test array and same thing.
  • html structure looks like this <div class="grid-item"> <div class="grid-container2"> <div class="grid-item2" data-tabid="1">1</div> <div class="grid-item2" data-tabid="2">2</div> <div class="grid-item2" data-tabid="3">3</div>
  • Do this change setTimeout(() => setClassNextItem(++index), 5000);
  • Thats it! Thank you very much!
  • Same thing happens. i edited my code from question,i removed loop from my code it is unnecessary. The dev-cc is close to solution.