zoukankan      html  css  js  c++  java
  • 第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>
    背景切换
  • 相关阅读:
    写给大数据开发初学者的话 | 附教程
    Mysql 到 Hbase 数据如何实时同步,强大的 Streamsets 告诉你
    如何学习大数据?阿里大数据开发师分享学习知识
    最简大数据Spark2.1.0
    从技术 Leader 的招聘需求看,如何转岗为当前紧缺的大数据相关人才?
    Redis内核原理及读写一致企业级架构深入剖析1综合组件环境实战
    为什么85%的大数据项目总是失败?
    js中的this关键字
    php百度api调用简单实例
    nginx常用命令
  • 原文地址:https://www.cnblogs.com/sellsa/p/9934556.html
Copyright © 2011-2022 走看看