简体   繁体   中英

JavaScript setTimeout() can't trigger itself

How can a function, which is triggered by another function, get the mouse's position? Here's my code:

function myFunction(e){
    setTimeout(function(){
        if(isMouseDown == true){
            mouseX = e.clientX;
            mouseY = e.clientY;
            document.getElementById('myElement').innerHTML = mouseX + ' , ' + mouseY;
            myFunction(event);
        } else {}
    }, 100);
}

What this does is to display the coordinates when clicked. I need it to display them every 100ms if isMouseDown == true .

Thanks

There is no way in Javascript for a random Javascript function to get the mouse position. The current mouse position only comes from an event object for a mouse-related event. So, if you want to keep track of the mouse position, then you can register an event handler for the mousemove event and for mousedown and mouseup to keep track of the button state.

If you only want to display the mouse position, ever 100ms, then you can set a timer so that it is only displayed that often, but you will need to keep track of the current mouse position in a mousemove event handler.

Here's a simple code example:

 var lastMouseX = 0, lastMouseY = 0; document.addEventListener("mousemove", function(e) { lastMouseX = e.clientX; lastMouseY = e.clientY; }); var mouseTimer; document.addEventListener("mousedown", function() { if (!mouseTimer) { mouseTimer = setInterval(function() { document.getElementById("x").innerHTML = lastMouseX; document.getElementById("y").innerHTML = lastMouseY; }, 100); } }); document.addEventListener("mouseup", function() { clearInterval(mouseTimer); mouseTimer = null; }); 
 <div id="x"></div> <div id="y"></div> 

It's a bit fuzzy what you're trying to achieve, however you're not going to get a periodic event if you're using setTimeout() . It sounds like you're looking for setInterval() . See the below example:

  var mouseX = 0; var mouseY = 0; var isMouseDown = true; document.onmousemove = function(e){ mouseX = e.pageX; mouseY = e.pageY; } setInterval("myFunction()", 100); function myFunction(){ if(isMouseDown) { document.getElementById('myElement').innerHTML = mouseX + ' , ' + mouseY; } } 
 <div id="myElement"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM