Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stepping through array with time delay

Tags:

javascript

I have tabs on my page each containing unique content. I want to automatically rotate the tabs and content without them being clicked upon. As soon as the page loads I want this function to begin using window.onload = function().

I have the following JavaScript array:

var HomeTabs = [1, 3, 5, 7, 9, 11]

I want to know how to show HomeTab 1 for 10 secs and then move to HomeTab 3 and then after 10 secs move to HomeTab 5 in that order, not random. when it gets to HomeTab 11 it then goes back to HomeTab 1 again.

I have a script to change the tab which is ChangeTab(1), where one is the number of the tab I want to show.

like image 516
neojakey Avatar asked May 06 '11 14:05

neojakey


People also ask

How to put delay in forEach?

forEach(delayLoop(display, 1000)); The end result is the same as before. Now you can use delayLoop() on any forEach() loop. Simply pass the function to use and the amount of time — in milliseconds — to delay between each iteration.

How can you delay the execution of the function FN by at least 1 second?

To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.

How do you wait for loop to finish?

To use Javascript promises in a for loop, use async / await . This waits for each promiseAction to complete before continuing to the next iteration in the loop.

How do you make a delay in JavaScript?

To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.


2 Answers

Use the setInterval method to call a function every ten seconds:

window.onload = function(){

  var HomeTabs = [1, 3, 5, 7, 9, 11];
  var index = 0;

  function nextTab() {
    ChangeTab(HomeTabs[index]);
    index = (index + 1) % HomeTabs.length;
  }

  nextTab();

  window.setInterval(nextTab, 10000);

};
like image 83
Guffa Avatar answered Oct 11 '22 23:10

Guffa


you can always use a setTimeout in a function, something like

function startRotating(currentIndex) {

  // do some checking on currentIndex

  setTimeout(function(){
      startRotating(currentIndex + jump)
  },10000);
}

that wont work as written, but you can expand it from there.

like image 33
hvgotcodes Avatar answered Oct 12 '22 00:10

hvgotcodes