延时执行:
setTimeout(函数,间隔时间); (时间为毫秒,比如1000);
<body>
<button id="button1">延时执行</button>
</body>
<script>
$("#button1").click(function(){
setTimeout(test,1000);
});
function test(){
console.log("延时执行");
};
</script>
<body>
<button id="button1">延时执行</button>
</body>
<script>
$("#button1").click(function(){
var text="沙丁鱼flat";
setTimeout(test(text),1000);
});
function test(text){
console.log("延时执行:"+text);
};
</script>
持续执行:
setInterval(函数,间隔时间); (时间为毫秒,比如1000);
clearInterval(持续执行的函数对象); ——用于停止持续间隔执行
Math.round(Math.random()*100) 随机毫秒0~100;
和延时执行同理,可带参也可无参,无参和延时一样,带参持续执行需要用其他方式,不能和延时一样,这里放一张带参的:
<body>
<button id="button1">持续执行</button>
<button id="button2">停止持续执行</button>
</body>
<script>
var interval;
$("#button1").click(function(){
var text="沙丁鱼flat";
interval=setInterval(function(){test(text);} ,Math.round(Math.random()*100));
});
$("#button2").click(function(){
clearInterval(interval);
console.log("停止间隔执行");
});
function test(text){
console.log("随机范围时间间隔执行:"+text);
};
</script>