Welcome

Hey there, welcome to my little space on the net.

Friday, December 18, 2020

javascript - throttles

I asked someone to write a throttle to restrict requests to the server and they didn't understand how. So I wrote this basic thing to show it. Sorry it's not pretty or anything, but here's two types of throttles in raw JS


// simplest lock - 1 request every x seconds


let timerLock = false; // this is the lock

const requestValues = []; // this is where all the data goes


var handleChange = (someValue) => {

  if(!timerLock){ timerLock = true; setTimeout(handleServerRequest, 4000) } // set the lock

  requestValues.push(someValue);

}


var handleServerRequest = () => {

  timerLock = false; // release the lock

  console.log(requestValues);

  console.log( 'fetch', requestValues.pop() )

  requestValues.length = 0; // clear the array

}

handleChange(1)

handleChange(2)

handleChange(3)

 

// fancier lock - trying to detect when the user stops typing

let timerLock = false; // this is the lock

const requestValues = []; // this is where all the data goes

let timerId = null;


var handleChange = (someValue) => {

  if(!timerLock){ timerLock = true; timerId = setTimeout(handleServerRequest, 300) } // set the lock

  else{

    clearTimeout(timerId); timerId = setTimeout(handleServerRequest, 300); // dont fire that request yet! set the timer again

  }

  requestValues.push(someValue);

}


var handleServerRequest = () => {

  timerLock = false; // release the lock

  console.log(requestValues)

  console.log( 'fetch', requestValues.pop() )

  requestValues.length = 0; // clear the array

}

handleChange(1)

setTimeout( () => { handleChange(2) }, 200 )

setTimeout( () => { handleChange(3) }, 400 )


No comments:

Post a Comment