Sayakiss Sayakiss - 2 months ago 8
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">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<video id="video" src="http://www.sample-videos.com/video/mp4/240/big_buck_bunny_240p_2mb.mp4" controls></video>

<script>
document.getElementById('video').addEventListener('volumechange', function () {
console.log('change')
//post a request to server to set default volume by ajax
})
</script>
</body>
</html>





But I find when a user change volume by drag, it will fire dozens request (check it by
change
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
volumechange
event.

My question:


  1. is it possible to send ajax only if it's the last
    volumechange
    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)?


Answer

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 https://davidwalsh.name/function-debounce

// 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.