简体   繁体   中英

javascript setTimeout() not waiting, even after calling as an anonymous function

I'm having a problem with setTimeout(), it doesn't seem to be waiting to call the function. Firstly i was using it like this:

function function1(driver){
  driver.get(secondaryUrl);
}

driver.get(initialUrl);
setTimeout(function1, 3000, driverInstance);

This was not working, it would just skip the delay. So i looked it up and apparently wrapping the function as an anonymous function would fix it. So I tried this:

function function1(driver){
  driver.get(secondaryUrl);
}

setTimeout(function(){ function1(driverInstance)}, 3000);

But this would do the same, just skip the delay and navigate to the second URL as soon as the first is loaded. Can anyone help me with a fix? Thanks

Remove the third parameter from this:

setTimeout(function1, 3000, driverInstance);

It should be:

setTimeout(function () {
    function1(driverInstance)
}, 3000);

I'm not sure if I understand you correctly, because there is missing variables declaration in your example. I assume you create object in JS with some method. And the you wish to call this method twice with some delay between. If so then code like this below should work. I've replaced get method into processUrl .

var url1 = 'http://something';
var url2 = 'http://another';

function Driver( url ) {
  this.processUrl = function( url ) {
    // some logic with URL
    console.log( url );
  }
}

var driver = new Driver()

driver.processUrl( url1 );

function fun1( instance ) {
  instance.processUrl( url2 )
}

setTimeout(fun1, 3000, driver);

or even simpler solution without using additional function:

var url1 = 'http://something';
var url2 = 'http://another';

function Driver( url ) {
  this.processUrl = function( url ) {
    // some logic with URL
    console.log( url );
  }
}

var driver = new Driver()

driver.processUrl( url1 );
setTimeout( driver.processUrl, 3000, url2 );

What is important here: lack of parentheses () . When you add parentheses at the end of function name it will immediately invoke function when code is process. You need to provide reference to function which should be invoked after 3 seconds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM