I have the code:

$(document).ready(function(){ $(this).movemouse(function(e){ console.log("X: " + e.pageX+" Y: "+e.pageY); }) }) 

I need the coordinates to be displayed on the console every 2 minutes, and not all the time while moving the mouse. Is it possible and in what direction to dig?

I tried setInterval() , but I did not achieve anything.

Second attempt:

 $(document).ready( function(){ var x=50; var y = 100; $(this).mousemove( function(e){ x = e.pageX; y = e.pageY; setInterval( function(){ console.log(x,y); }, 5000); }) }) 
  • I changed the code a little, but the variable is output to the console anyway many times, is it because of multithreading? Is it possible to cope with it somehow? $(document).ready(function(){ var x=50; var y = 100; $(this).mousemove(function(e){ x = e.pageX; y = e.pageY; setInterval(function(){ console.log(x,y); },5000); }) }) - XTreme95
  • the function inside the mousemove is often performed often when the mouse is moved. And each time it starts its own interval - you have hundreds of timer branches. No, JS is not yet multi-threaded in the general case. - Sergiks

1 answer 1

The position of the mouse can only be obtained from mouse events, for example, mousemove . Therefore, let the listener of this event work all the time, but does not immediately bring it to the console, but simply updates the variable. And on the timer output to the console the value of this variable every 2 minutes.

PS jQuery for this is not necessary at all - you just need to listen to the event of the mousemove document, update the variable and setInterval() .


Something like this:

 var myMouse = { x: null, y: null }; // тут держим координаты function mouseMoved(e) { // обновляет координаты в переменной выше myMouse.x = e.pageX; myMouse.y = e.pageY; } function mouseDisplay() { // выводит из переменной, что там есть document.body.innerHTML += '<br>' + myMouse.x +':'+ myMouse.y; } document.addEventListener('mousemove', mouseMoved); // слушаем событие window.setInterval( mouseDisplay, 1200); // запускаем таймер