0

Is there some sort of window.onThis(); function that I can set so that my code runs in a loop in the background?

window.onload = function() {while(true) {console.log("Blah")}}

This makes the page unresponsive. What is the recommended method of doing this?

I feel something's going over my head. Perhaps I'm looking at it the wrong way.

1

2 Answers 2

2

Javascript can only run one thread at a time, so when it is running console.log ("Blah") forever as fast as possible, it is unable to do anything else.

A better way would be to use setInterval, e.g.

var a  = setInterval(function () { console.log("blah"); }, 1000);
// Set the function to be called every 1000 milliseconds

//(optional) some time later
clearInterval(a);
// Stop the function from being called every second.

In general, a busy infinite loop ( while (true) { ... } ) is never a good idea.

See https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval

Sign up to request clarification or add additional context in comments.

1 Comment

How do Javascript/Canvas games update so fast? What do they do to update the display every frame yet not lag the page up?
0

It makes the page unresponsive because you've created an infinite loop. The while loop condition will always be true therefore the loop will never stop running.

I think you are looking for setInterval(), see here https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval

Comments

Your Answer

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.