• 第8天-setInterval/setTimeout


    setInterval是什么?

    setInterval()方法重复调用一个函数或执行一个代码段,在每次调用之间具有固定的时间延迟。

    setInterval(函数,间隔时间)

    例如

    function fn(){
        document.write('hello world <br/>');
    }
    
    setInterval(fn, 1000); //注意函数名不能加()

    获取随机数字

    知识点:

          开启定时器,会返回一个定时器id:   timer = setInterval(函数,时间)

          根据返回的id,清除该定时器: clearInterval(timer)

          开启定时器之前,先清除之前的定时器

    var oIpt = document.getElementById('ipt');
    var startBtn = document.getElementById('start');
    var stopBtn = document.getElementById('stop');
    var timer = null;
    
    //随机数方法
    function getRandomInt(min, max){
        return Math.floor(Math.random()*(max-min+1)+min);
    }
    
    //点击开始按钮, 表单不停的填入随机数
    startBtn.onclick = function(){
        //开始定时器之前,先清除之前的定时器
        //如果不先清除,会出现,点击多次开始按钮,会生成多个定时器,而结束的时候,只能清除最后一个定时器,导致之前的定时器还在跑,停不下来
        clearInterval(timer);
        //定时器会返回一个id,这样后面我们就能通过通过timer知道是哪个定时器,然后进行清除
        timer = setInterval(function(){
            //获取20-40的随机整数
            var randomInt = getRandomInt(20, 40);
            //把随机数放入到表单中
            oIpt.value = randomInt;
        }, 100)
    }
    
    //点击结束按钮,清除定时器
    stopBtn.onclick = function(){
        clearInterval(timer);
    }
    获取随机数字
    <button>切换背景</button>
    <button>停止</button>
    
    <script>
        var aBtn = document.getElementsByTagName('button');
        var timer = null;
        
        aBtn[0].onclick = function(){
            clearInterval(timer);
            timer = setInterval(function(){
                var randomInt = getRandomInt(1000, 1999);
                document.body.style.background = "url(https://img.infinitynewtab.com/wallpaper/" + randomInt + ".jpg) no-repeat";
                document.body.style.backgroundSize = "100%";
            }, 1000)
        }
        
        aBtn[1].onclick = function(){
            clearInterval(timer);
        }
        
        function getRandomInt(min, max){
            return Math.floor(Math.random()*(max -min + 1) + min)
        }
    </script>
    背景切换
  • 相关阅读:
    JENKINS安装及布署
    Python的函数返回多值其实就是返回一个tuple!
    函数参数类型
    软件配置管理工作范围
    PYTHON学习:关键字raise
    Java绘图: 使用 Graphics 类绘制线段、矩形、椭圆/圆弧/扇形、图片、文本
    An error occurred while updating the entries. See the inner exception for details.
    SQL 查询 VS LinQ
    Vue3.x中使用 elementplus 的各种方式
    C# Cannot insert explicit value for identity column in table 'ServiceOrderReceipt' when IDENTITY_INSERT is set to OFF.
  • 原文地址:https://www.cnblogs.com/sellsa/p/9934556.html
Copyright © 2020-2023  润新知