Skip to content

feross/function-with-timeout

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

function-with-timeout travis npm downloads javascript style guide

Ensure a function is always called within a timeout period

Accepts a function as input and returns a new function. If the returned function is called before the timeout period (the default timeout is one second), it clears the timeout and invokes the input function. If the returned function isn't called before the timeout period, the input function is called regardless.

Works in the browser, with browserify! Module development sponsored by Study Notes.

install

npm install function-with-timeout

usage

Say you're using Google Analytics and you want to send a beacon when a form is submitted. The problem is that in most browsers, XHR requests are canceled when the page is unloaded, which will happen on form submission. So, we want to block the page navigation to give time for the beacon to be sent.

But we also don't want the form submit to fail if the Analytics server never responds or the library fails to load.

Here's what we can do:

var functionWithTimeout = require('function-with-timeout')

form.addEventListener('submit', function (event) {
  // prevent form submission
  event.preventDefault()

  // send analytics beacon
  ga('send', 'event', 'Signup Form', 'submit', {
    // submit the form when beacon request is sent or 1000ms has elapsed,
    // whichever comes first
    hitCallback: functionWithTimeout(function () {
      form.submit()
    })
  })
})

license

MIT. Copyright (c) Feross Aboukhadijeh.

About

Ensure a function is always called within a timeout period

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project

 

Packages

No packages published

Contributors 3

  •  
  •  
  •