2013-10-22 50 views
-2

我有这样的代码在设定的时间间隔刷新图像:如何在设定时间后停止一个JavaScript刷新

<img src="http://somwhere/picture.jpg" id="refreshimage1" onload=”setTimeout('document.getElementById(\'refreshimage1\').src=\'http://somwhere/picture.jpg?\'+new Date().getMilliseconds()', 15000)" width="400" border="1" /> 

的问题是,我需要的图像,每15秒刷新,伟大的工程。但是......我一夜之间离开了网页,今天在Firefox中拥有15GB的缓存,并且我的c:\驱动器上没有可用空间。 (每页大约有20张图片,全部使用这个清爽的代码

那么,有没有办法添加到这段代码,并让它在设定的时间后停止?像5分钟后,也许它会停止刷新图像?

+4

是的,添加逻辑来跟踪时间。 – epascarello

+0

有两件事情,你应该将'onload'登录到你的JavaScript文件/脚本元素之一 - 这是一个内联代码块的逻辑。其次,你不需要通过id来获取图像,因为'this'会引用你的图像。 – megawac

+0

为什么你需要15秒刷新间隔?我觉得无论如何,你都可以在不消耗太多带宽和缓存的情况下实现愿望的效果。 – PlantTheIdea

回答

0

工作和测试代码。这将会让你的图像只有5次。

<img src="http://somwhere/picture.jpg" id="refreshimage1" onload="fnSetTimer()" width="400" border="1" /> 

将这个功能您的脚本标签中。

var c = 0; 

function fnSetTimer() 
{ 
//do whatever you want to do here. 
//document.getElementById('refreshimage1').src = 'http://somwhere/picture.jpg?\'' + new Date().getMilliseconds(); 
alert("testing"); 
var t = setTimeout(fnSetTimer,15000); 
c=c+1; 
if(c>5) 
clearTimeout(t); 
} 

魔法门这会帮助你。

+0

嘿迈克,似乎无法得到刷新实际工作。但我的旧线代码刷新仍然有效。我错过了什么?由于空间的原因,我将下面的代码粘贴到另一个评论中(对格式化感到抱歉,它将它全部压在一起) – Rich

+0

Rich

+0

给我一点时间。 –

0

试试吧。

var c = 0; 
function fnSetTimer() 
{ 
alert("testing"); 
var t = setTimeout(fnSetTimer,15000); 
c=c+1; 
if(c>5) 
clearTimeout(t); 
} 
0

这是我现在在哪里。使用定时器功能,无法获取图像刷新。

<script> 
var c = 0; 
function fnSetTimer() 
{ 
document.getElementById('refreshimage1').src='http://68.116.42.142:8080/cam_4.jpg?\'+new Date().getMilliseconds(); 
var t = setTimeout(fnSetTimer,5000); 
c=c+1; 
if(c>5) 
clearTimeout(t); 
} 
</script> 
<img src="http://68.116.42.142:8080/cam_4.jpg"; id="refreshimage1" onload="fnSetTimer()" width="400" /> 

<img src="http://68.116.42.142:8080/cam_4.jpg"; id="refreshimage2" onload="setTimeout('document.getElementById(\'refreshimage2\').src=\'http://68.116.42.142:8080/cam_4.jpg?\'+new Date().getMilliseconds()', 5000)" width="400" /> 

第二个img src代码是刷新图像的原始代码,仍然有效。并排放置,您可以看到顶部图像是静态的,底部图像每5秒继续更新一次。所以图像的URL很好,只是缺少一些东西在定时器脚本中刷新?

相关问题