Skip to content

Instantly share code, notes, and snippets.

@ikenfin
Created September 20, 2016 10:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ikenfin/d6eefb100b183da8b61d38d7686d4039 to your computer and use it in GitHub Desktop.
Save ikenfin/d6eefb100b183da8b61d38d7686d4039 to your computer and use it in GitHub Desktop.
Пример определения ухода пользователя
/*
Очередь фиксированного размера
*/
function fixedSizeQueue(size) {
var queue = Array.apply(null, []);
queue.fixedSize = size;
queue.trimHead = fixedSizeQueue.trimHead;
queue.push = fixedSizeQueue.push;
return queue;
}
// усечение длины очереди
fixedSizeQueue.trimHead = function() {
if(this.length <= this.fixedSize)
return;
Array.prototype.splice.call(this, 0, (this.length - this.fixedSize));
}
// запихивание элемента в очередь
fixedSizeQueue.push = function() {
var result;
result = Array.prototype.push.apply(this, arguments);
this.trimHead(this);
return result;
}
/*
Функция определения направления основанная на подсчете очков
*/
function whereDidHeGo(coords) {
var scores = {
up : 0,
down : 0
}
, i = 0
, len = coords.length;
for(; i < len - 1; i++) {
if(coords[i] > coords[i+1])
scores.up++;
else
scores.down++;
}
return scores.up > scores.down ? 'up' : 'down';
}
$(function() {
//инициализация всего и вся
var $OUT_DELAY = null /* переменная для хранения таймера */
, storage = fixedSizeQueue(20)
, lastTick = Date.now()
, tickDelay = 10 /* ms - время между логированием координат */
, navigateToCloseBtnTime = 432 /* ms - примерное время довода курсора от body до крестика */
, $body = $('body');
$body.on('mousemove', function(e) {
var nowIs = Date.now();
if((+lastTick) + (+tickDelay) < (+nowIs)) {
storage.push(e.clientY);
lastTick = nowIs;
}
});
$body
.on('mouseleave', function(e) {
// если курсор ушел с <body> - ждем navigateToCloseBtnTime мс и выполняем код
$outDelay = setTimeout(function() {
var direction = whereDidHeGo(storage);
if(direction == 'up') {
// ЗДЕСЬ КОД КОТОРЫЙ БУДЕТ ВЫЗВАН ПРИМЕРНО ПЕРЕД ЗАКРЫТИЕМ ВКЛАДКИ
// выключаем события отлова координат
$body.off('mouseleave mouseenter');
alert('Подождите! У нас есть для вас оффер!');
}
}, navigateToCloseBtnTime)
})
.on('mouseenter', function() {
// если курсор вернулся до таймаута сбрасываем таймаут, т.о. продолжаем отлов координат
clearTimeout($outDelay);
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment