User Tools

Site Tools


Javascript loop N times with interval

The function code will execute into js closures.

loop.js
#!/usr/bin/env node
 
int = 1020;
 
function doSetTimeout(n, arg) {
    setTimeout(function() { 
        // some work code
        console.log("start service " + arg + " after " + n * int + " msec"); 
    },
    n * int);
}
 
var list = [ 'a', 'b', 'c', 'd'];
 
for (var i = 1; i <= list.length; i++) {
    doSetTimeout(i-1, list[i-1]);
}
 
//EOF

Output

# ./loop.js
start service a after 0 msec
start service b after 1020 msec
start service c after 2040 msec
start service d after 3060 msec

Page

index.html.ep
% layout 'default';
% title 'Bird';
 
<h5>Mojolicious</h5>
 
<div id="log" class="callout"></div>
 
<script>
int = 1020;
 
function doSetTimeout(n, arg) {
    setTimeout(function() { 
        data = "start service " + arg + " after " + n * int + " msec " + "<br/>"; 
        $("#log").append(data);
    },
    n * int);
}
 
var list = [ 'a', 'b', 'c', 'd'];
for (var i = 1; i <= list.length; i++) {
  doSetTimeout(i, list[i-1]);
}
</script>
%#EOF

Result page


First PagePrevious PageBack to overviewNext PageLast Page