setinterval函数是怎样的呢?下面就让我们一起来了解一下吧:
setInterval其实就是一个实现定时调用的函数,它的用法也就是能够根据指定的周期(一般是以毫秒来计算)来调用函数或是计算表达式。setInterval方法通常是会不停地调用函数的,直到clearInterval被调用或是窗口被关闭。
语法格式:
setInterval(code,millisec[,"lang"])
参数:
code 必需。需要调用的函数或者要执行的代码串。
millisec 必需。周期性执行或者调用 code 之间的时间间隔,以毫秒计。
lang 可选。 JScript | VBScript | JavaScript
说明:1000 毫秒= 1 秒。
参考范例:
<!DOCTYPE html>
<html>
<body>
<form>
<input type="text" id="clock" size="35" />
<script>
var int=self.setInterval("clock()",50)
function clock(){var t=new Date()
document.getElementById("clock").value=t
}
</script>
</form>
<div id="clock"></div>
<button onclick="int=window.clearInterval(int)">Stop interval</button>
</body>
</html>
以上就是小编的分享了,希望能够帮助到大家。
javascript定时器setInterval的基本用法
大家啊可能经常在各大网站上看到这样一个功能就是跳动的时钟,一秒一秒的不停的变化。今天这个小分享呢就给大家分享一下怎么用javascript来实现这种随处可见的小功能
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><title> New Document </title><meta name="Generator" content="EditPlus"><meta name="Author" content=""><meta name="Keywords" content=""><meta name="Description" content=""><script type="text/javascript">/******************* setInterval(代码块/函数,执行周期以毫秒为单位)函数 自动的不停的调用某个固定的函数,直到遇到由其本身 返回的ID值并且结合clearInterval(参数为setInterval的返回值)的调用时停止 ************************/ //下面以用setInterval函数实现跳动的时钟作为案例讲解 //定义一个全局变量 存储定时器 这个就是serInterval()函数将要返回的IDvar thread = "";//这个函数的作用是将最新的日期赋值给文本款显示出来function go() {document.getElementById("a").value = new Date().toLocaleString();}function f() {//在启动定时器的时候 将定时器存储在全局变量当中便于停止//此时用serInterval()函数来定时的执行go函数从而达到时钟跳动的功能thread = setInterval("go()", 1000);//每隔多少时间执行(无需递归自动执行),单位毫秒数1000毫秒等于1秒}function stop() {//停止setIterval定时器的方法时clearInterval(参数)//这个地方就用到了clearInterval()并且把thread参数传进去以达到停止定时器setInterval的作用clearInterval(thread);}</script></head><body><input type="text" id="a" style="width:300px;height:50px;font-size:23px" /><br /><input type="button" value="开始定时器" onclick="f()" /><input type="button" value="停止定时器" onclick="stop()" /></body></html>