I have a react application, I have an event listener set so that when a user types, an autosave function is triggered. The trouble is, I don't want api calls being fired on each event. Ideally I'd want it to poll the API every 3 seconds or so when a user is typing.
I have the following code currently:
window.setTimeout(function() {
window.setInterval(function() {
console.log(data);
this.actions.autoSave(data);
}, 3000);
}, 3000);
As you can imagine that's not quite what I'm after. So I just wondered what the best approach would be?
I have a react application, I have an event listener set so that when a user types, an autosave function is triggered. The trouble is, I don't want api calls being fired on each event. Ideally I'd want it to poll the API every 3 seconds or so when a user is typing.
I have the following code currently:
window.setTimeout(function() {
window.setInterval(function() {
console.log(data);
this.actions.autoSave(data);
}, 3000);
}, 3000);
As you can imagine that's not quite what I'm after. So I just wondered what the best approach would be?
Share Improve this question asked Sep 5, 2015 at 11:59 Ewan ValentineEwan Valentine 3,9618 gold badges46 silver badges72 bronze badges 02 Answers
Reset to default 6This is a generic throttle function:
var functionName = (function () {
'use strict';
var timeWindow = 500; // time in ms
var lastExecution = new Date((new Date()).getTime() - timeWindow);
var functionName = function (args) {
// your code goes here
};
return function () {
if ((lastExecution.getTime() + timeWindow) <= (new Date()).getTime()) {
lastExecution = new Date();
return functionName.apply(this, arguments);
}
};
}());
if you connect it to your case lets say the user types in a textarea and you saved a variable for it named userText.
you can do this:
userText.addEventListener("keyup", function(e){
functionName(userText.innerText);
},false);
this will throttle the calls to your api, if you added your logic to the inner function with the ment // your code goes here.
Example debounce from https://github./Terebinth/Vickers/blob/master/lib/vickers__workshop.coffee
set_boundingRect: ->
@forceUpdate()
bounding_rect = React_DOM.findDOMNode(@).getBoundingClientRect()
@setState
view_width: bounding_rect.width
view_height: bounding_rect.height
x: bounding_rect.width / 2 # transform coordinate system
y: bounding_rect.height / 2 # translation of coordinate
debounce: (func, wait, immediate) ->
timeout = 'scoped here'
->
context = @
args = arguments
later = ->
timeout = null
if not(immediate) then func.apply(context, args)
callNow = immediate and not(timeout)
clearTimeout(timeout)
timeout = setTimeout(later, wait)
if callNow then func.apply(context, args)
debounced_set_boundingRect: -> @debounce(@set_boundingRect, 100)()