Guide

Working examples

Every live Debounce preview with its explanation and the complete, copyable source files of each one.

Each preview is the same one shown on Home and Examples, and runs the real package. The copied files load the published browser bundle, so they work as they are.

SearchLive preview

debounce waits 300 ms of quiet, Enter runs the pending search at once with flush(), and Escape drops it with cancel().

Type to search.

    Explore the code

    HTML / CDN

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Search after the user stops typing</title>
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <label for="search">Search a fruit</label>
          <input id="search" type="text" autocomplete="off" />
          <p id="status" aria-live="polite">Type to search.</p>
          <ul id="results"></ul>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/debounce@1.0.2/dist/browser/debounce.global.js"></script>
        <script src="./main.js" defer></script>
      </body>
    </html>
    

    CSS

    style.css
    ul {
      padding-left: 1.25rem;
    }
    #status {
      color: #666;
    }
    

    JavaScript

    main.js
    const { debounce } = window.Debounce
    const fruits = [
      'apple',
      'apricot',
      'banana',
      'blueberry',
      'cherry',
      'grape',
      'mango',
      'melon',
      'orange',
      'peach',
      'pear',
      'plum',
    ]
    const input = document.querySelector('#search')
    const status = document.querySelector('#status')
    const results = document.querySelector('#results')
    
    const search = debounce(query => {
      const matches = fruits.filter(fruit => fruit.includes(query.trim().toLowerCase()))
      results.replaceChildren(
        ...matches.map(fruit => Object.assign(document.createElement('li'), { textContent: fruit }))
      )
      status.textContent = query.trim()
        ? `${matches.length} results for “${query.trim()}”`
        : 'Type to search.'
    }, 300)
    
    input.addEventListener('input', () => search(input.value))
    input.addEventListener('keydown', event => {
      if (event.key === 'Enter') search.flush()
      if (event.key === 'Escape') search.cancel()
    })
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Search after the user stops typing</title>
        <style>
          ul {
            padding-left: 1.25rem;
          }
          #status {
            color: #666;
          }
        </style>
      </head>
      <body>
        <main>
          <label for="search">Search a fruit</label>
          <input id="search" type="text" autocomplete="off" />
          <p id="status" aria-live="polite">Type to search.</p>
          <ul id="results"></ul>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/debounce@1.0.2/dist/browser/debounce.global.js"></script>
        <script>
          const { debounce } = window.Debounce
          const fruits = [
            'apple',
            'apricot',
            'banana',
            'blueberry',
            'cherry',
            'grape',
            'mango',
            'melon',
            'orange',
            'peach',
            'pear',
            'plum',
          ]
          const input = document.querySelector('#search')
          const status = document.querySelector('#status')
          const results = document.querySelector('#results')
    
          const search = debounce(query => {
            const matches = fruits.filter(fruit => fruit.includes(query.trim().toLowerCase()))
            results.replaceChildren(
              ...matches.map(fruit =>
                Object.assign(document.createElement('li'), { textContent: fruit })
              )
            )
            status.textContent = query.trim()
              ? `${matches.length} results for “${query.trim()}”`
              : 'Type to search.'
          }, 300)
    
          input.addEventListener('input', () => search(input.value))
          input.addEventListener('keydown', event => {
            if (event.key === 'Enter') search.flush()
            if (event.key === 'Escape') search.cancel()
          })
        </script>
      </body>
    </html>
    

    Package / ESM

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Search after the user stops typing</title>
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <label for="search">Search a fruit</label>
          <input id="search" type="text" autocomplete="off" />
          <p id="status" aria-live="polite">Type to search.</p>
          <ul id="results"></ul>
        </main>
        <script type="module" src="./main.js"></script>
      </body>
    </html>
    

    CSS

    style.css
    ul {
      padding-left: 1.25rem;
    }
    #status {
      color: #666;
    }
    

    JavaScript

    main.js
    import { debounce } from '@samline/debounce'
    
    const fruits = [
      'apple',
      'apricot',
      'banana',
      'blueberry',
      'cherry',
      'grape',
      'mango',
      'melon',
      'orange',
      'peach',
      'pear',
      'plum',
    ]
    const input = document.querySelector('#search')
    const status = document.querySelector('#status')
    const results = document.querySelector('#results')
    
    const search = debounce(query => {
      const matches = fruits.filter(fruit => fruit.includes(query.trim().toLowerCase()))
      results.replaceChildren(
        ...matches.map(fruit => Object.assign(document.createElement('li'), { textContent: fruit }))
      )
      status.textContent = query.trim()
        ? `${matches.length} results for “${query.trim()}”`
        : 'Type to search.'
    }, 300)
    
    input.addEventListener('input', () => search(input.value))
    input.addEventListener('keydown', event => {
      if (event.key === 'Enter') search.flush()
      if (event.key === 'Escape') search.cancel()
    })
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Search after the user stops typing</title>
        <style>
          ul {
            padding-left: 1.25rem;
          }
          #status {
            color: #666;
          }
        </style>
      </head>
      <body>
        <main>
          <label for="search">Search a fruit</label>
          <input id="search" type="text" autocomplete="off" />
          <p id="status" aria-live="polite">Type to search.</p>
          <ul id="results"></ul>
        </main>
        <script type="module">
          import { debounce } from '@samline/debounce'
    
          const fruits = [
            'apple',
            'apricot',
            'banana',
            'blueberry',
            'cherry',
            'grape',
            'mango',
            'melon',
            'orange',
            'peach',
            'pear',
            'plum',
          ]
          const input = document.querySelector('#search')
          const status = document.querySelector('#status')
          const results = document.querySelector('#results')
    
          const search = debounce(query => {
            const matches = fruits.filter(fruit => fruit.includes(query.trim().toLowerCase()))
            results.replaceChildren(
              ...matches.map(fruit =>
                Object.assign(document.createElement('li'), { textContent: fruit })
              )
            )
            status.textContent = query.trim()
              ? `${matches.length} results for “${query.trim()}”`
              : 'Type to search.'
          }, 300)
    
          input.addEventListener('input', () => search(input.value))
          input.addEventListener('keydown', event => {
            if (event.key === 'Enter') search.flush()
            if (event.key === 'Escape') search.cancel()
          })
        </script>
      </body>
    </html>
    

    Autosave at most once per second

    AutosaveLive preview

    throttle saves immediately, then at most once per second while typing, and once more with the final text.

    Not saved yet.

    Explore the code

    HTML / CDN

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Autosave at most once per second</title>
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <label for="note">Note</label>
          <textarea id="note" rows="4"></textarea>
          <p id="saved" aria-live="polite">Not saved yet.</p>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/debounce@1.0.2/dist/browser/debounce.global.js"></script>
        <script src="./main.js" defer></script>
      </body>
    </html>
    

    CSS

    style.css
    textarea {
      width: 100%;
    }
    

    JavaScript

    main.js
    const { throttle } = window.Debounce
    const note = document.querySelector('#note')
    const saved = document.querySelector('#saved')
    let saves = 0
    
    const save = throttle(() => {
      saves += 1
      saved.textContent = `Saved ${saves} times · ${note.value.length} characters`
    }, 1000)
    
    note.addEventListener('input', save)
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Autosave at most once per second</title>
        <style>
          textarea {
            width: 100%;
          }
        </style>
      </head>
      <body>
        <main>
          <label for="note">Note</label>
          <textarea id="note" rows="4"></textarea>
          <p id="saved" aria-live="polite">Not saved yet.</p>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/debounce@1.0.2/dist/browser/debounce.global.js"></script>
        <script>
          const { throttle } = window.Debounce
          const note = document.querySelector('#note')
          const saved = document.querySelector('#saved')
          let saves = 0
    
          const save = throttle(() => {
            saves += 1
            saved.textContent = `Saved ${saves} times · ${note.value.length} characters`
          }, 1000)
    
          note.addEventListener('input', save)
        </script>
      </body>
    </html>
    

    Package / ESM

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Autosave at most once per second</title>
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <label for="note">Note</label>
          <textarea id="note" rows="4"></textarea>
          <p id="saved" aria-live="polite">Not saved yet.</p>
        </main>
        <script type="module" src="./main.js"></script>
      </body>
    </html>
    

    CSS

    style.css
    textarea {
      width: 100%;
    }
    

    JavaScript

    main.js
    import { throttle } from '@samline/debounce'
    
    const note = document.querySelector('#note')
    const saved = document.querySelector('#saved')
    let saves = 0
    
    const save = throttle(() => {
      saves += 1
      saved.textContent = `Saved ${saves} times · ${note.value.length} characters`
    }, 1000)
    
    note.addEventListener('input', save)
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Autosave at most once per second</title>
        <style>
          textarea {
            width: 100%;
          }
        </style>
      </head>
      <body>
        <main>
          <label for="note">Note</label>
          <textarea id="note" rows="4"></textarea>
          <p id="saved" aria-live="polite">Not saved yet.</p>
        </main>
        <script type="module">
          import { throttle } from '@samline/debounce'
    
          const note = document.querySelector('#note')
          const saved = document.querySelector('#saved')
          let saves = 0
    
          const save = throttle(() => {
            saves += 1
            saved.textContent = `Saved ${saves} times · ${note.value.length} characters`
          }, 1000)
    
          note.addEventListener('input', save)
        </script>
      </body>
    </html>
    

    Update a progress bar once per frame

    Scroll progressLive preview

    rafThrottle turns a burst of scroll events into one update per animation frame.

    Scroll this box.

    A long article.

    Explore the code

    HTML / CDN

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Update a progress bar once per frame</title>
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <div
            id="bar"
            role="progressbar"
            aria-label="Reading progress"
            aria-valuemin="0"
            aria-valuemax="100"
            aria-valuenow="0"
          ></div>
          <div id="article">
            <p>Scroll this box.</p>
            <p style="height: 60rem">A long article.</p>
          </div>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/debounce@1.0.2/dist/browser/debounce.global.js"></script>
        <script src="./main.js" defer></script>
      </body>
    </html>
    

    CSS

    style.css
    #article {
      height: 12rem;
      overflow-y: auto;
      border: 1px solid #ccc;
    }
    #bar {
      height: 0.375rem;
      width: 0;
      background: #6d28d9;
    }
    

    JavaScript

    main.js
    const { rafThrottle } = window.Debounce
    const article = document.querySelector('#article')
    const bar = document.querySelector('#bar')
    
    const update = rafThrottle(() => {
      const max = article.scrollHeight - article.clientHeight
      const progress = max > 0 ? Math.round((article.scrollTop / max) * 100) : 0
      bar.style.width = progress + '%'
      bar.setAttribute('aria-valuenow', String(progress))
    })
    
    article.addEventListener('scroll', update, { passive: true })
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Update a progress bar once per frame</title>
        <style>
          #article {
            height: 12rem;
            overflow-y: auto;
            border: 1px solid #ccc;
          }
          #bar {
            height: 0.375rem;
            width: 0;
            background: #6d28d9;
          }
        </style>
      </head>
      <body>
        <main>
          <div
            id="bar"
            role="progressbar"
            aria-label="Reading progress"
            aria-valuemin="0"
            aria-valuemax="100"
            aria-valuenow="0"
          ></div>
          <div id="article">
            <p>Scroll this box.</p>
            <p style="height: 60rem">A long article.</p>
          </div>
        </main>
        <script src="https://cdn.jsdelivr.net/npm/@samline/debounce@1.0.2/dist/browser/debounce.global.js"></script>
        <script>
          const { rafThrottle } = window.Debounce
          const article = document.querySelector('#article')
          const bar = document.querySelector('#bar')
    
          const update = rafThrottle(() => {
            const max = article.scrollHeight - article.clientHeight
            const progress = max > 0 ? Math.round((article.scrollTop / max) * 100) : 0
            bar.style.width = progress + '%'
            bar.setAttribute('aria-valuenow', String(progress))
          })
    
          article.addEventListener('scroll', update, { passive: true })
        </script>
      </body>
    </html>
    

    Package / ESM

    HTML

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Update a progress bar once per frame</title>
        <link rel="stylesheet" href="./style.css" />
      </head>
      <body>
        <main>
          <div
            id="bar"
            role="progressbar"
            aria-label="Reading progress"
            aria-valuemin="0"
            aria-valuemax="100"
            aria-valuenow="0"
          ></div>
          <div id="article">
            <p>Scroll this box.</p>
            <p style="height: 60rem">A long article.</p>
          </div>
        </main>
        <script type="module" src="./main.js"></script>
      </body>
    </html>
    

    CSS

    style.css
    #article {
      height: 12rem;
      overflow-y: auto;
      border: 1px solid #ccc;
    }
    #bar {
      height: 0.375rem;
      width: 0;
      background: #6d28d9;
    }
    

    JavaScript

    main.js
    import { rafThrottle } from '@samline/debounce'
    
    const article = document.querySelector('#article')
    const bar = document.querySelector('#bar')
    
    const update = rafThrottle(() => {
      const max = article.scrollHeight - article.clientHeight
      const progress = max > 0 ? Math.round((article.scrollTop / max) * 100) : 0
      bar.style.width = progress + '%'
      bar.setAttribute('aria-valuenow', String(progress))
    })
    
    article.addEventListener('scroll', update, { passive: true })
    

    Complete file

    index.html
    <!doctype html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Update a progress bar once per frame</title>
        <style>
          #article {
            height: 12rem;
            overflow-y: auto;
            border: 1px solid #ccc;
          }
          #bar {
            height: 0.375rem;
            width: 0;
            background: #6d28d9;
          }
        </style>
      </head>
      <body>
        <main>
          <div
            id="bar"
            role="progressbar"
            aria-label="Reading progress"
            aria-valuemin="0"
            aria-valuemax="100"
            aria-valuenow="0"
          ></div>
          <div id="article">
            <p>Scroll this box.</p>
            <p style="height: 60rem">A long article.</p>
          </div>
        </main>
        <script type="module">
          import { rafThrottle } from '@samline/debounce'
    
          const article = document.querySelector('#article')
          const bar = document.querySelector('#bar')
    
          const update = rafThrottle(() => {
            const max = article.scrollHeight - article.clientHeight
            const progress = max > 0 ? Math.round((article.scrollTop / max) * 100) : 0
            bar.style.width = progress + '%'
            bar.setAttribute('aria-valuenow', String(progress))
          })
    
          article.addEventListener('scroll', update, { passive: true })
        </script>
      </body>
    </html>