• 0

[JS] Multiple setTimeouts


Question

Is there a more elegant way to do something like this?

setTimeout( gotoSlide,    520,  "side-ID-1");
setTimeout( gotoSlide,   1300,  "side-ID-2" );
setTimeout( gotoSlide,   2800,  "side-ID-3" );
setTimeout( gotoSlide,   5420,  "side-ID-4" );
setTimeout( gotoSlide,   6111,  "side-ID-5" );
setTimeout( gotoSlide,   6222,  "side-ID-6" );
setTimeout( gotoSlide,   7999,  "side-ID-7" );
setTimeout( gotoSlide,  12004,  "side-ID-8" );
setTimeout( gotoSlide,  16032,  "side-ID-9" );
...
setTimeout( gotoSlide,  941002,  "side-ID-150" );

Assume I may have up to 150 slides that I need to go to on a timeline that's not always at a fixed interval, and I don't want to write 150 lines of the setTimeout()  function.  In my example I have (520, 1300, 2800, 5420, 6111, 6222, 7999, etc.), and you can imagine this will be a long list of timeouts. 

Since the argument for the gotoSlide()  function uses a string like "side-ID-###", where the ### value is linear, incrementing from 1, I'm wondering if this could be done in some kind of loop, where the timeout interval value is derived from an array.  --That's my assumption at least.

Not sure how to write that code.  Could someone help me?

Link to comment
https://www.neowin.net/forum/topic/1428242-js-multiple-settimeouts/
Share on other sites

6 answers to this question

Recommended Posts

  • 0
  On 21/04/2023 at 13:27, primortal said:

Take a look at Automatic Slideshow, https://www.w3schools.com/howto/howto_js_slideshow.asp

Expand  

Thanks, but it's not really a slideshow that I'm using. I only use that in my example to obfuscate my actual function. The slideshow example that you gave won't work because that works on the fix time; my function needs to be called on different intervals, e.g. 520, 1300, 2800, 5420, 6111, 6222, 7999 ... 941002

 

  • 0
function gotoSlide(id) {
  ...
}
const timeouts = [520, 1300, 2800, 5420, 6111, 6222, 7999, 12004, 16032, ..., 941002]
timeouts.forEach((t, index) => setTimeout(gotoSlide, t, `side-ID-${index+1}`))

Another approach is to only set the next timeout after a slide has been displayed, although I don't think there is any limit to the number of timeouts you can set at one time.

const timeouts = [520, 1300, 2800, 5420, 6111, 6222, 7999, 12004, 16032, 941002]

function displaySlide(id) {
  console.log('display slide', id)
}

function gotoSlide(index) {
  const id = `side-ID-${index+1}`
  displaySlide(id)
  if (index === timeouts.length-1) 
    return // end of timeouts, so don't display any more
  const t = timeouts[index+1]-timeouts[index]
  console.log('t', t)
  setTimeout(gotoSlide, t, index+1);
} 

setTimeout(gotoSlide, timeouts[0], 0)

 

  • 0
  On 21/04/2023 at 23:53, virtorio said:
function gotoSlide(id) {
  ...
}
const timeouts = [520, 1300, 2800, 5420, 6111, 6222, 7999, 12004, 16032, ..., 941002]
timeouts.forEach((t, index) => setTimeout(gotoSlide, t, `side-ID-${index+1}`))

Another approach is to only set the next timeout after a slide has been displayed, although I don't think there is any limit to the number of timeouts you can set at one time.

const timeouts = [520, 1300, 2800, 5420, 6111, 6222, 7999, 12004, 16032, 941002]

function displaySlide(id) {
  console.log('display slide', id)
}

function gotoSlide(index) {
  const id = `side-ID-${index+1}`
  displaySlide(id)
  if (index === timeouts.length-1) 
    return // end of timeouts, so don't display any more
  const t = timeouts[index+1]-timeouts[index]
  console.log('t', t)
  setTimeout(gotoSlide, t, index+1);
} 

setTimeout(gotoSlide, timeouts[0], 0)

 

Expand  

Thank you this is exactly what I was looking for. Can I ask with setTimeout(), is there a way to pause them all in one go and then resume them if need be? I'm not sure if setTimeout() has that capability

  • 0
  On 22/04/2023 at 04:17, Brian Miller said:

Thank you this is exactly what I was looking for. Can I ask with setTimeout(), is there a way to pause them all in one go and then resume them if need be? I'm not sure if setTimeout() has that capability

Expand  

There is no way to pause a timeout (as far as I know), but you can cancel one. You can probably achieve what you want by keeping track of the current timeout and index, such as in the example below:

const slideController = {
  _timeout: 0, 
  timeouts: [520, 1300, 2800, 5420, 6111, 6222, 7999, 12004, 16032, 941002],  
  current: 0,  
  gotoSlide(id) {
    console.log('goto page', id)
  },
  next() {
    const c = this.current
    this.gotoSlide(`slide-id-${c+1}`)
    if (c === this.timeouts.length-1) return
    this.current++
    this._timeout = setTimeout(() => this.next(), this.timeouts[this.current]-this.timeouts[c])
  },
  pause() {
    clearTimeout(this._timeout)
  },
  resume() {
    this.next()
  },
  start() {
    setTimeout(() => this.next(), this.timeouts[0])
  }
}

slideController.start()

// to pause
// slideController.pause()

// to resume
// slideController.resume()

 

  • Like 3

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Lets assume that we are capitalists and right wing people for a sec. - The individual should be able to accrue wealth and no government should limit that wealth growth. - That same individual should not be taxed any higher than the average person. Tax is a socialist construct to help those in that country who are less fortunate, and it limits wealth growth. - This individual should be able to do whatever they want to do with their money and have no restrictions, as it would otherwise limit wealth growth. So having said all that with the mindset of a capitalist and small government political leaning, he can do what he want with it. Some billionaires have little pet projects to inflate their self worth like rocket ships and stuff, this is just a bit different is al, and probably the more compassionate of choices. I think he's seen a need, and that need isn't in the USA.
    • I'm concerned about this, too. How can he make sure that the money is actually used for good instead of ending up in the pockets of crooked politics and warlords? I think that's a problem.
    • Sony unveils its first fight stick 'Project Defiant', supports PC and PS5 by Pulasthi Ariyasinghe In a surprise twist, Sony announced a new piece of hardware at its State of Play presentation today. Currently going by the codename Project Defiant, it is Sony's first attempt at making a fight stick. Considering the company is currently partnered with Marvel to make a first-party fighting game featuring heroes and villains from the popular comic universe, this seems to be the right time to unveil the project. As seen in the teaser trailer above, the wireless fight stick follows the modern black and white PlayStation hardware style of the consoles and standard gamepad controllers. The controller will ship with a toolless design for changing the restrictor gates, with square, circle, and octagon options incoming for the stick. Meanwhile, the buttons are confirmed to have mechanical switches. Plus, a dedicated touchpad, much like on the DualSense controller, is available on the top of the fight stick. "It’s built in a sturdy, ergonomic design for a comfortable feel during intense fight sessions," adds the company. Sony is leveraging its PlayStation Link technology in the device. With it, the company is promising ultra-low latency wireless connectivity, making sure it provides players "precise in-game response to each button press and digital stick movement." Interestingly, PlayStation Link is Sony's proprietary wireless connectivity standard designed for PlayStation 5's audio transmissions, which is now being used a little differently for this piece of hardware. The controller has built-in storage for holding both the restrictor gates and the PS Link USB adapter. As expected, a wired connection is also possible, with a USB-C port available on the device for connecting to a PlayStation 5 or PC. To make sure the device remains in good condition during travel, Sony is throwing in a sturdy sling carry case with each Project Defiant fight stick. More details, like the official name, internal hardware, release date, and most importantly, price, will be revealed later. The hardware has a 2026 launch window right now.
  • Recent Achievements

    • First Post
      James courage Tabla earned a badge
      First Post
    • Reacting Well
      James courage Tabla earned a badge
      Reacting Well
    • Apprentice
      DarkShrunken went up a rank
      Apprentice
    • Dedicated
      CHUNWEI earned a badge
      Dedicated
    • Collaborator
      DarkShrunken earned a badge
      Collaborator
  • Popular Contributors

    1. 1
      +primortal
      351
    2. 2
      snowy owl
      167
    3. 3
      +FloatingFatMan
      164
    4. 4
      ATLien_0
      162
    5. 5
      Xenon
      128
  • Tell a friend

    Love Neowin? Tell a friend!