$0.2

Is it possible to run 2 threads on javascript?

Ask a question+
0

Hey i am working on a little game that counts how many times you clicked on an image in 30 seconds. I have 2 separate functions, one function generates a new location to the image and updates the player score, and the other one count down from 30 seconds and updates the “Clicked” paragraph.

The problem is that i can’t seem to run 2 functions at the same time I done some research and i saw that js can only run one thread so how is this possible to do?

<html>
<head>
</head>
<body>
    <img id='ball' src="ball.png" alt="Logo"style="position: absolute; top: 450px; left: 900; width:70px;height:70px;" onclick="moveBall()">
    <p id="demo"></p>
    <p id="timer"></p>
    <p id="Clicks" style="font-family: Impact, Charcoal, sans-serif; font-size:150px; color:brown;">0</p>
    <script>
        function moveBall()
        {
            var ball = document.getElementById("ball");
            ball.style.left = Math.floor(Math.random() * 1500);
            ball.style.top = Math.floor(Math.random() * 900)
            document.getElementById('Clicks').innerHTML = parseInt(document.getElementById('Clicks').innerHTML) + 1;
            if(document.getElementById('Clicks').innerHTML == 20)
            {
                document.body.style.backgroundColor = "#68a2ff";
                document.getElementById('Clicks').style.color = '#ff688d';
            }
        }
        function sleep() 
        {
            var start = new Date().getTime();
            var finish = start + 20;
            while(finish - start != 0)
            {
                document.getElementById('timer').innerHTML = finish - start;
            }

        } 
    </script>
</body>
</html>
add comment

0 Answer

Your Answer