Sayakiss Sayakiss - 3 months ago 13
Ajax Question

How to check a event which is the last event?

I want to storage the default volume for every user of a video(by posting ajax to server then storage it into DB), and I write this:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<video id="video" src="" controls></video>

document.getElementById('video').addEventListener('volumechange', function () {
//post a request to server to set default volume by ajax

But I find when a user change volume by drag, it will fire dozens request (check it by
logs in console)... It's dirty(and resource consuming) to send dozens ajax to server, and the only useful ajax is which triggered by the last

My question:

  1. is it possible to send ajax only if it's the last
    event? If it possible, then how to implement that?

  2. If question 1 is impossible or needing a lot of working, how to work around(post several(not dozens) ajax is acceptable)?


You need to use a "debounce". This is the same technique that's used in auto-complete or type-ahead text boxes. There are plenty of implementations and libraries which do this.

To explain a debounce, you set a timeout and reset it each time an event fires. If enough time elapses since the last event, trigger the behaviour.

The example I copied was from

// Create the listener function
var updateLayout = _.debounce(function(e) {

    // Does all the layout updating here

}, 500); // Maximum run of once per 500 milliseconds

// Add the event listener
window.addEventListener("resize", updateLayout, false);

You'll notice the example uses _. This is because this is also a function in the underscore library.