测试定时器、获取字符串的字节长度

测试定时器

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            #txt{
                width:300px;
                height:300px;
                display: block;
                margin:100px  auto;
            }
        </style>
        <script>
            window.onload=function(){
                var oTxt=document.getElementById("txt");
                var timer=null;
                var oldT=new Date().getTime();       //老时间
                timer=setInterval(function(){
                    var now=new Date().getTime();  //新时间
                    oTxt.value+=now-oldT+'\n';      //存放时间差
                    oldT=new Date().getTime();  
                },1000);
                document.onclick=function(){
                    clearInterval(timer);
                }
            }
        </script>
    </head>
    <body>
        <textarea id="txt" rows="30" cols="30"></textarea>
    </body>
</html>

 

获取字符串的字节长度:

 

<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script>
            var str='abc啊';
            function getByLon(str,type){
                var res=0;
                for(var i=0;i<str.length;i++){
                    if(str.charAt(i)>='\u4e00'&&str.charAt(i)<='\u9fa5'){  //在4e00到9fa5之间的字符
                        if(type=='utf-8'){  //utf-8,字符加3
                            res+=3;
                        }else{res+=2;}    //其他字符加2
                    }else{res++}         //不在4e00到9fa5之间的字符
                }
                return res;
            }
            alert(getByLon(str,'utf-8'));
        </script>
    </head>
    <body>
    </body>
</html>

 

posted @ 2016-07-25 21:09  河南小样  阅读(185)  评论(0编辑  收藏  举报