1

I have read on w3schools:

  • The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.

  • The setTimeout() method will wait the specified number of milliseconds, and then execute the specified function.

I tried them both. However, that is not what I need.

I want a function that will loop continuously until the time duration is reached.

Is there a workaround on this? Thanks!

0

2 Answers 2

3
var start = new Date();
var timer_id = setInterval(function() {
  // the duration is 10 seconds
  if (new Date() - start > 10000) {
     clearInterval(timer_id);
  } else {
     your_function();
  }
}, 1000); // every 1 second your function will run, you could change it by your needs.
Sign up to request clarification or add additional context in comments.

Comments

2

You can do this without any setTimeouts or setIntervals:

var t1 = new Date().getTime();
var interval = 100;
while(new Date().getTime() - t1 < interval){
    // do stuff;
}

This will loop continuously for 100 ms.

3 Comments

Since there's no sleep function, this loop will take all your CPU. Also, other timeouts won't fire in some JavaScript engines, because they're single threaded and require the outer function to return before firing timeouts and intervals. See the solution by xdazz
so the answer of xDazz is better?
Well the OP stated that he wanted the function to "loop continuously", so I deliberately suggested a solution when virtually nothing else would be executed whilst this function is looping.

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.