Для получения полного доступа

Все сниппеты с тэгами «JavaScript, throttling»

Gravatar image
Vitaly Dyatlov
  • Репутация: 1
  • Сниппеты: 1
  • Ревизии: 0

Often happens that you want to log some events on frontend, but those events happen very often.. What to do if you don't want to kill your server and user's bandwidth? A sample throttling technique for onScroll event. Can be used for example to record current position of user on the page (to record reading progress).

Note, that if event happens very often then it might be that payload wont be executed ever and in this case you can consider to use another solution, based on current time (record current time and if next event happens in less than expected timeout, then skip it).

	var payload = function() {
		p = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());
		$.post('/path/to/handler', {"progress": p});
	var t;
		// actual throttling happens here
		if( t ) {
			clearTimeout( t );
		t = setTimeout(payload, 1000 /* 1 second */); // call payload function once per second