开发者

'onmousedown' not being called in JavaScript

开发者 https://www.devze.com 2023-04-07 17:16 出处:网络
In Javascript, I want to create a handler for a mouse click. Then, I want to be able to \"busy-wait\" for a few seconds before running the next line of code.* But in the \"busy-wait\", I want to still

In Javascript, I want to create a handler for a mouse click. Then, I want to be able to "busy-wait" for a few seconds before running the next line of code.* But in the "busy-wait", I want to still be able to process the mouse click events.

Why will the following code run the while loop entirely and THEN activate the handler? (as in, why doesn't the mouse click handler event ever get called in the middle of the busy-wait while loop?)

<html>
    <body>
        <p id="debugMessageElement"> </p>

        <script type="text/javascript">
            canvas=document.createElement("canvas")
            var ctx = canvas.getContext("2d");
            canvas.width = 840;
            canvas.height = 560;
            document.body.appendChild(canvas);

            var mouse_input = function(event){
                document.getElementById("debugMessageElement").innerHTML = event.pageX + ", " + event.pageY + "<br />"
            }

            canvas.onmousedown = mouse_input;

            timeallowed = 3
            start = Date.now()
            while(true){
                now = Date.now()
                delta = now - start
                if(delta >= timeallowed*1000){
                    document.write("" + timeallowed + " seconds has pas开发者_开发问答sed")
                    break;
                }
            }
        </script>
    </body>
</html>

*The reason that I'm designing my code like the above is ultimately because I want to do something like this:

for(p in person){
    for(t in person[p].shirts){
        busy_wait_5_seconds() //However, I want to process mouse clicks in these five seconds.
        //THEN move on to the next shirt... After five seconds...
    }
}

P.S. if you're going to test this code, please note that I used the HTML5 canvas, so some browsers might not work?


JavaScript has only a single thread. If you do a while-true loop, it will essentially freeze the entire page until the code stops running.

To wait a certain time before executing some code, you should use setTimeout. The final solution to your problem is a little more complicated than that though - you would need a recursive setTimeout to process the loop.

edit: Here's something I quickly whipped up which should solve your nested loop with waiting in the sub loop: http://jsfiddle.net/t4gsR/ - It may go a bit over your head if you're still a beginner though, but press "run" on the top menu and see it work :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号