简体   繁体   中英

PHP is executing a javascript on mouse move over window. It's looping on a function. How can I make it execute only once?

Basically, I have to execute a function on JS, that uses a variable in PHP. The problem I'm having is that the function on JS is executing constantly. I need the function to execute when the mouse moves over the page, which works great, except it executes in loop non-stop.

I'm pasting an example code. Any ideas on how to make it execute the JS function only once? Any help would be greatly appreaciated, I'm not very good at PHP & JS.

<?php 

function page()

{

echo 'test text';
}
//page()
?>

<html>
<head>

<title>onmousemove test</title>

<script type="text/javascript">

window.onmousemove = move;
function move() {
    alert("<?PHP page() ?>");
}
</script>
</head>

Use a flag. check if the flag is set, if not, execute the code, then set the flag.

var stop = false; //flag

function move(){
    if(stop) return; //is the flag true?
    alert("<?PHP page() ?>"); //it wasn't, so alert
    stop = true; //now set it to true so it doesn't fire again
}

It's not looping non-stop, it's just looping whenever you move your mouse... You should consider window.onload instead, this fires automatically when the page is done load. But since in this post you insist window.onmousemove , you can try this:

triggered = false;

function move() {
  triggered = true;
  alert("<?php page(); ?>");
}

window.onmousemove = function(){ 
  if (triggered === false) move();
};

JSFiddle

(PS Since you're knew, I'll tell you something. To except an answer, you click the green check mark, this gives both of us reputation).

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