admin管理员组

文章数量:1431935

I'm encountering a problem with setTimeout, and I can't figure out why.

I'm using cordova, and the setTimeout function leads to curious portment.

app.displayData = function(device) {
    app.readThermometer(device);
    app.readAccelerometer(device);
    app.readHumidity(device);
    app.readMagnetometer(device);
    //setTimeout(app.displayData(device), 5000);
};

This is executed once.

app.displayData = function(device) {
    app.readThermometer(device);
    app.readAccelerometer(device);
    app.readHumidity(device);
    app.readMagnetometer(device);
    setTimeout(app.displayData(device), 5000);
};

This is executed many times, but way faster than once every 5 seconds. It is a problem for me because it prevent jQuery from executing correctly. (Never getting the dom modification expected)

What am I missing? If it is a bug in cordova, do you know other way to delay code execution in javascript?

I'm encountering a problem with setTimeout, and I can't figure out why.

I'm using cordova, and the setTimeout function leads to curious portment.

app.displayData = function(device) {
    app.readThermometer(device);
    app.readAccelerometer(device);
    app.readHumidity(device);
    app.readMagnetometer(device);
    //setTimeout(app.displayData(device), 5000);
};

This is executed once.

app.displayData = function(device) {
    app.readThermometer(device);
    app.readAccelerometer(device);
    app.readHumidity(device);
    app.readMagnetometer(device);
    setTimeout(app.displayData(device), 5000);
};

This is executed many times, but way faster than once every 5 seconds. It is a problem for me because it prevent jQuery from executing correctly. (Never getting the dom modification expected)

What am I missing? If it is a bug in cordova, do you know other way to delay code execution in javascript?

Share Improve this question asked Jul 15, 2014 at 8:05 RichardRichard 1,0511 gold badge12 silver badges29 bronze badges 2
  • why do you want to delay code execution? What do you want to do? The second code will run infinitely as it is a recursive call. You need to use the setTimeout call outside app.displayData – frank Commented Jul 15, 2014 at 8:12
  • yes, I know. It's my purpose to make it run infinitely :). I'm getting a continuous flow of data, and i'm trying to update them. – Richard Commented Jul 15, 2014 at 8:17
Add a ment  | 

1 Answer 1

Reset to default 4

You're calling the function app.displayData directly

setTimeout(app.displayData(device), 5000);

Try the following instead

setTimeout(function () {
    app.displayData(device);
}, 5000);

And another alternative if you prefer Function.bind

setTimeout(app.displayData.bind(app, device), 5000);

本文标签: javascriptcordova setTimeout functionStack Overflow