setInterval() for an analogue clock

和自甴很熟 提交于 2019-12-24 08:20:04

问题


I'm quite new to JavaScript and I have trouble working with etInterval().

I'm creating an analogue clock as an exercise. I have a function setTime() that gets and displays the time by rotating the arrows accordingly.

I want to execute this function again and again.

Here is my code :

    $(document).ready(function(){

        function setTime(){
            var d = new Date();
            var hour = d.getHours();
            var minute = d.getMinutes();
            var hourRotation = hour * 30 + (minute / 2);
            var minuteRotation = minute * 6;
            $("#small").css({
                "-webkit-transform": "rotate(" + hourRotation + "deg)",
                "-moz-transform": "rotate(" + hourRotation + "deg)",
                "-o-transform": "rotate(" + hourRotation + "deg)"
            });
            $("#big").css({
                "-webkit-transform": "rotate(" + minuteRotation + "deg)",
                "-moz-transform": "rotate(" + minuteRotation + "deg)",
                "-o-transform": "rotate(" + minuteRotation + "deg)"
            });
        };
        function clockStart(){
            setInterval(setTime(),1000);
            setTime();
        }
        clockStart();
    });

I'd like to understand this method and how to use it. The examples I could find looked so obvious, but still I can't make it work.


回答1:


You are making a function call in setInterval().

What you want to do is :

setInterval(setTime,1000);



回答2:


when you call you setInterval function, you don't pass the function reference as a parameter, but it's return value.
So you should use:

setInterval(setTime,1000);

or

setInterval(function(){setTime()},1000);



回答3:


The function setTime() in the line setInterval(setTime(),1000); is getting evaluated before the setInterval() function is called, and the results of the evaluation of setTime() are passed to the setInterval() function as an argument, rather than the function istelf being passed as an argument.

What you need to do is replace the function call ("setTime()") with this name of the function ("setTime") like this: setInterval(setTime, 1000);



来源:https://stackoverflow.com/questions/6774027/setinterval-for-an-analogue-clock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!