1

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 !!!!
 }
 document.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.

asked May 19, 2011 at 18:40

4 Answers 4

2

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.

answered May 19, 2011 at 18:45
Sign up to request clarification or add additional context in comments.

1 Comment

This works really well, muntoo's didn't really work because the browser froze while doing it so the image change wasn't even visible.
2

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.

answered May 19, 2011 at 18:51

Comments

1
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.

answered May 19, 2011 at 18:43

Comments

1

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.

answered May 19, 2011 at 18:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.