Pausing for a split moment in JavaScript
I have the following JavaScript code:
var cILo=true;
var img1="images/title-2a.png";
var img2="images/title-2b.png";
function loadblinker() {
for (var i=0,l=Math.floor(Math.random()*10);i<l;++i) {
cILo=!cILo;
if (cILo) {
document.getElementById("lamp").src=img1;
} else {
document.getElementById("lamp").src=img2;
}
!!!! THIS LINE HERE !!!!
}
doc开发者_如何学Goument.getElementById("lamp").src=img1;
setTimeout("loadblinker()",Math.floor(Math.random()*10000));
}
Where I have marked the code with the phrase "!!!! THIS LINE HERE !!!!", I need some way to pause the execution for a split second. This code, when it is done, is going to give the appearance of a short circuiting light (light in the video games). I was wondering as to how I would pause the code seeing as there appears to be no natural method.
I think a better approach would be to eliminate the for loop by using setInterval
. You could then clear the interval after Math.floor(Math.random()*10)
iterations. I wouldn't recommend blocking execution by just spinning in a loop. Most browsers freak out when you do that.
Typically this is handled in JavaScript by calling setTimeout, passing it the code to be executed after the delay. Or in other words, instead of pausing within a function, you break your function in two: one part to be executed before the delay and the next part to be executed after.
You are already recursively calling your function via setTimeout, so you are almost there. See if you can restructure your code so that you get rid of the for loop and instead pass in the maximum number of iterations. Decrement that counter on each call. If after the decrement, your counter is greater than zero, call setTimeout to call the function again.
function pause(ms)
{
var d = new Date();
var c = null;
do
{
c= new Date();
}
while(c - d < ms);
}
Use pause(1000);
to pause for 1 second.
Courtesy of this website.
Javascript in browsers does not have the ability to do a synchronous pause. You can hack your way around it, as muntoo suggested, but you shouldn't do it.
精彩评论