Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Trying to create a simple timer but cannot get it to work.


JavaScript
var timer = -50;
    boolean lock = true;

    while(lock == true){
    timer++;
        if(timer == 50){
            lock = false;
        }
    }

    while(lock == false){
    timer--;
        if(timer == -50){
            lock = true;
        }
    }


What I have tried:

When I remove this code my program runs normally.
Posted
Updated 21-Feb-18 14:40pm
v2
Comments
j snooze 21-Feb-18 17:21pm    
Why would you not use the javascript setInterval function? Its got a built in timer you can tell it to run a function every x milliseconds?
Example...this would run every 3 seconds(since the time parameter is in milliseconds)

setInterval(function(){ alert("Hello World!"); }, 3000);
A_Griffin 21-Feb-18 18:55pm    
What are you expecting your code to do? All I can see is a variable (timer) that, in the blink of an eye, will "count" from -50 to +50 and back again, then the code ends.

1 solution

Quote:
When I remove this code my program runs normally.

You forgot to tell what is the problem with this code.

Quote:
Trying to create a simple timer but cannot get it to work.

As far as I can see, this code only hog CPU. Its problem is that its speed is different on every computer and with today computers, it will be so fast you will barely see something.

As of today every computer offer some efficient timing service which is used for every anime you see, even video.
Window setInterval() Method[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900