Loop timer in JavaScript

Asked
Active3 hr before
Viewed126 times

7 Answers

timerjavascript
90%

Note that setTimeout and setInterval are very different functions:,Both functions return a timer ID which you can use to abort the timeout. All you have to do is store that value in a variable and use it as argument to clearTimeout(tid) or clearInterval(tid) respectively.,setInterval(f, t) calls the the argument function, f, once every t milliseconds.,setInterval will execute the code forever, in intervals of the provided timeout.

So, depending on what you want to do, you have two valid choices:

// set timeout
var tid = setTimeout(mycode, 2000);

function mycode() {
   // do some stuff...
   tid = setTimeout(mycode, 2000); // repeat myself
}

function abortTimer() { // to be called when you want to stop the timer
   clearTimeout(tid);
}

or

// set interval
var tid = setInterval(mycode, 2000);

function mycode() {
   // do some stuff...
   // no need to recall the function (it's an interval, it'll loop forever)
}

function abortTimer() { // to be called when you want to stop the timer
   clearInterval(tid);
}
load more v
88%

setInterval(function() {
   //this code runs every second 
}, 1000);
load more v
72%

The clearInterval() method stops the executions of the function specified in the setInterval() method.,The clearTimeout() method stops the execution of the function specified in setTimeout().,The second parameter indicates the length of the time-interval between each execution.,The clearInterval() method uses the variable returned from setInterval():

Timing Events

The window object allows execution of code at specified time intervals.

window
load more v
65%

OK! Now that we've seen all that, here is an example of this code at work for looping a function called drawText with a delay of 2 seconds between each loop:, If we wish to cancel the looping, we can use the appropriately named clearInterval function:, Creating Web Animations BUY ,To see setInterval in action in some other realistic examples on this site itself, check out the bottom of the Creating a Sweet Content Slider article as well as the Creating an Analog Clock article. They both feature setInterval quite prominently!

The setTimeout function allows us to delay executing some code. The way we use it is quite nice. This function allows us to specify what code to execute and how many milliseconds to wait before the code we specified executes. Putting that into JavaScript, it will look something like this:

let timeoutID = setTimeout(someFunction, delayInMilliseconds);
load more v
75%

When Node.js starts, it initializes the event loop, processes the provided input script (or drops into the REPL, which is not covered in this document) which may make async API calls, schedule timers, or call process.nextTick(), then begins processing the event loop.,For example, if we run the following script which is not within an I/O cycle (i.e. the main module), the order in which the two timers are executed is non-deterministic, as it is bound by the performance of the process:,To get around this, the 'listening' event is queued in a nextTick() to allow the script to run to completion. This allows the user to set any event handlers they want.,You can't emit an event from the constructor immediately because the script will not have processed to the point where the user assigns a callback to that event. So, within the constructor itself, you can use process.nextTick() to set a callback to emit the event after the constructor has finished, which provides the expected results:

The following diagram shows a simplified overview of the event loop's order of operations.

   ┌───────────────────────────┐┌─ > │timers││└─────────────┬─────────────┘│┌─────────────┴─────────────┐││ pending callbacks││└─────────────┬─────────────┘│┌─────────────┴─────────────┐││ idle, prepare││└─────────────┬─────────────┘┌───────────────┐│┌─────────────┴─────────────┐│ incoming: │││poll│ < ─────┤connections, ││└─────────────┬─────────────┘│data, etc.││┌─────────────┴─────────────┐└───────────────┘││check││└─────────────┬─────────────┘│┌─────────────┴─────────────┐└──┤ close callbacks│└───────────────────────────┘
load more v
40%

JavaScript doesn’t offer any wait command to add a delay to the loops but we can do so using setTimeout method. This method executes a function, after waiting a specified number of milliseconds. Below given example illustrates how to add a delay to various loops:,How to add a delay in a JavaScript loop?,How to select a random element from array in JavaScript ?,How to ignore loop in else condition using JavaScript ?

22%

At this point, the loop is over, our setTimeout() functions are still counting down, and all that remains in the call stack is console.log(‘The loop is done!’).,Notice that we placed our loop completion check within the setTimeout() function, not within the main body of the for loop.,We can simply wrap loopDone() in a setTimeout() to address this.,Another option is to check when the console.log(i) statements are done.

What does this code output?

for (var i = 1; i < 6; i++) {
   setTimeout(function() {
      console.log(i);
   }, 1000);
}
console.log('The loop is done!');
load more v