Note that there are some explanatory texts on larger screens.

plurals
  1. POPassing arguments to setInterval is causing strange behaviour
    text
    copied!<p>I'm making a simple script reads out the nginx server status in node.js I don't think my problem has to do with node.js itself, but more an issue with how I'm using the setInterval() function.</p> <p>I don't want to paste all the code, because that makes a bit confusing to read. When you run this code, you see this:</p> <pre><code>pre-Timer for web25 pre-Timer for web26 pre-Timer for web27 pre-Timer for web28 pre-Timer for web29 Timer for web29 Fetch host? web29 Timer for web29 Fetch host? web29 Timer for web29 Fetch host? web29 Timer for web29 Fetch host? web29 Timer for web29 Fetch host? web29 </code></pre> <p>As you can see, the timer is only using the last host of the loop. Somehow it's not making a copy of the variable to the setInterval scope.</p> <p>What am I doing wrong?</p> <p><strong>Part of the code:</strong></p> <pre><code>var http = require('http'); StatsNginxMapper.prototype = { nginxServers: new Object(), mysql: null, mysqlClient: null, statsDb: 'serverstats', userMapper: null, init: function() { this.mysql = require('mysql'); this.mysqlClient = /* mysql stuff */; this.collectData(); }, setUserMapper: function(mapper) { this.userMapper = mapper; }, collectData: function() { this.collectServers(); }, collectServers: function() { var self = this; var server = null; /* Normally this is done through MySQL, but for now lets do it manually */ server = new StatsNginxServer(); server.setHost('web25'); this.nginxServers['web25'] = server; server = new StatsNginxServer(); server.setHost('web26'); this.nginxServers['web26'] = server; server = new StatsNginxServer(); server.setHost('web27'); this.nginxServers['web27'] = server; server = new StatsNginxServer(); server.setHost('web28'); this.nginxServers['web28'] = server; server = new StatsNginxServer(); server.setHost('web29'); this.nginxServers['web29'] = server; this.loopServers(); }, loopServers: function() { for(var host in this.nginxServers) { var nginxServer = this.nginxServers[host]; if(nginxServer.hasTimer()) continue; var self = this; console.log('pre-Timer for ' + host); var timerId = setInterval(function() { console.log('Timer for ' + host); self.getData(host); }, 2000); nginxServer.setTimer(timerId); } }, getData: function(host) { console.log('Fetch host? ' + host); }, </code></pre> <p>}</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload