开发者

How short can this script be and still achieve the same thing - display a message "loading.." followed by an extra period every 1 second for 7 seconds [closed]

开发者 https://www.devze.com 2023-03-24 21:58 出处:网络
Closed. This question needs to be more focused. It is not currently accepting answers. 开发者_JAVA技巧
Closed. This question needs to be more focused. It is not currently accepting answers.
开发者_JAVA技巧

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 8 years ago.

Improve this question
<script>

    var dot = ".";
    var counter = 0;
    var message = "Loading Page";

    function writeLoadingMessage(){
        if (counter > 6) return;

        setTimeout('writeMessage();',1000);

    }

    function writeMessage(){

        document.getElementById('loadingMessageSpan').innerHTML = message + dot;
        message += dot
        counter++
        writeLoadingMessage();

        }

</script>


<BODY>

    <span style="font-weight:bold;" id="loadingMessageSpan"></span>

    <SCRIPT>writeLoadingMessage();</SCRIPT>
</BODY>


(function(){var i=6,a=setInterval(function(){document.getElementById('loadingMessageSpan').innerHTML+=".";!i--&&clearInterval(a);},1E3)})()

You will need to have Loading already in your span tag. As a note it is pointless to worry about getting it this small though. Also, the page will will have to be already loaded.


If you want it shorter: http://jsfiddle.net/pimvdb/wBFSy/.

<script>
    var counter = 0;

    function writeMessage() {
        document.getElementById('loadingMessageSpan').innerHTML += ".";

        if(++counter < 7) {
            setTimeout(writeMessage, 1000);
        }
    }

    window.onload = writeMessage;
</script>

<body>
    <span style="font-weight:bold;" id="loadingMessageSpan">Loading Page</span>
</body>

Minifying also helps :)

var a=0;function b(){document.getElementById("loadingMessageSpan").innerHTML+=".";++a<7&&setTimeout(b,1E3)}window.onload=b


1) User setInterval instead.

2) Just set the message once and append . to end

3) Put all the js at the bottom

<body>    
<span style="font-weight:bold;" id="loadingMessageSpan">Loading Page</span>    
<script type="text/javascript">
    var counter = 0;
    var id = setInterval(function(){
        document.getElementById('loadingMessageSpan').innerHTML += ".";
        if(++counter>6) {
            clearInterval(id);
        }
    }, 1000);
</script>
</body>


If you really want it short you can go this route:

<BODY>
    <span style="font-weight:bold;" id="loadingMessageSpan">Loading Page</span>
    <script>
        var counter = 0;
        var interval = setInterval(function(){
          document.getElementById('loadingMessageSpan').innerHTML += ".";
          if(++counter > 6)
            clearInterval(interval);
        },1000)
    </script>
</BODY>

http://jsfiddle.net/kc3fb/2/

0

精彩评论

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