• 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

    • how big is your HDD that only has 100gb left? I take it this the main drive.  Is this a pc or laptop? I ask because changing hdd in pcs are much easier. You sure a good clean/purge of data wouldn't clear up space - have you ran disk cleanup? Which is part of windows..  You can for sure move data to your external drive, install programs to it, etc - but using it to store updates?   
    • How to record screen as GIF in Windows 11 by Taras Buria The Snipping Tool app is already quite a capable program for screenshots and screen recordings. Still, there is always room for improvement, and many users agree that the app needs the ability to save screen recordings as GIFs. Microsoft heard those users, and recent updates introduced the long-requested feature, allowing you to record your screen as a GIF. Here is how to do it. Record screen as a GIF in Windows 11 Note: By the time of publishing this article, GIF support in Snipping Tool is only available to Windows Insiders. However, you can enable that feature on stable Windows 11 releases as well; here is how: Go to store.rg-adguard.net, select ProductID in the first drop-down, paste 9MZ95KL8MR0L into the search box, and select Fast in the last drop-down. Press the checkmark button. Find and download Microsoft.ScreenSketch_2022.2505.21.0_neutral_~_8wekyb3d8bbwe.msixbundle in the list of apps. The version number could be newer, just make sure you are downloading an msixbundle file. Note that the browser will warn you about downloading a potentially harmful file. Open the file and click Update. Download ViveTool from GitHub and unpack the files in a convenient and easy-to-find folder. Run Command Prompt as Administrator and navigate to the folder containing the ViveTool files with the CD command. For example, if you have placed ViveTool in C:\Vive, type CD C:\Vive. Type vivetool /enable /id:47081492 and press Enter. The steps above might seem a bit tedious, but that is the only way to get GIF support in Snipping Tool without enrolling your device in the Windows Insider program. We will update the article once the feature is publicly available, so there is no need to jump through all the hoops just to make it work. Tip: You can always roll back Snippint Tool to the latest version from the Microsoft Store by uninstalling it and downloading it again. Now, with GIF support enabled in Snipping Tool, here is how to save a screen recording as a GIF in Windows 11: Press Win + Shift + S, select screen recording mode and record whatever you want. After the recording is over, Snipping Tool will open your video so that you can view, trim, or save it. At this point, all you have to do is click the GIF button in the upper-right corner. On the next screen, select your GIF quality and click Export to save as a file or Copy to copy it to the clipboard. And that is how you save screen recordings as GIFs in Windows 11. Note that Snipping Tool can only save GIFs for up to 30 seconds. Anything beyond that will be cut off. You might think that Clipchamp, Windows 11's built-in video editor, is a good option when you want to save a screen recording as a GIF. However, it really sucks at that. The video duration is capped at just 15 seconds, which is even worse than the Snipping Tool, and the output resolution is hilariously low. The latter makes it impossible to distinguish any details, and all you get is a blurry, pixelated mess. No, Clipchamp is not a good option for that. If you want to create GIFs that are longer than 30 seconds, a good option is to go with apps like ShareX, which is extremely flexible and customizable (and also free, which makes it one of our favorite must-have apps for Windows 11). Alternatively, you can record a video using the Snipping Tool and then convert it to a GIF using web-based services like Ezgif, another great free utility. Keep in mind that the larger your video resolution and the longer its duration, the bigger the final GIF size. Depending on the settings, GIFs could reach hundreds of megabytes, so you have to set your expectations correctly (and so do the settings, too).
    • I'll give you an example of "the settings problem." As awful as the HP Smart app is, it's magnitudes more useful than Settings when I need to do some deep dive stuff on my HP Officejet.
    • I hate to defend Apple but this marketing and they are only "desperate" to move from #3 to #1 for biggest company in the world.
    • There's very granular stuff in the legacy Control Panel that will probably never be accessible from settings. But that stuff will still be there if you know where to look.
  • Recent Achievements

    • Week One Done
      habso earned a badge
      Week One Done
    • Week One Done
      DXB APPS earned a badge
      Week One Done
    • One Month Later
      DecaffKnight94 earned a badge
      One Month Later
    • Dedicated
      S.P earned a badge
      Dedicated
    • One Month Later
      adxnksd42031 earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      661
    2. 2
      ATLien_0
      252
    3. 3
      Michael Scrip
      235
    4. 4
      Steven P.
      150
    5. 5
      +FloatingFatMan
      148
  • Tell a friend

    Love Neowin? Tell a friend!