简体   繁体   中英

setTimeout not executing the passed function

I'm working on a simple interface for testers to use, which I'm writing as an HTML page. What I need to do is open a specific URL when the user presses a button (the URL triggers a Hudson/Jenkins job on another server). Here is the code I'm using to accomplish this:

function triggerJob() {
  var url = "...";
  var trigger = window.open(url);
  setTimeout(function() {trigger.close();}, 1000);
}

A couple of notes:

  • I know this a bad way of accomplishing what I want to do. I have already implemented the solution using jQuery, and for some reason the job on the Hudson server does not get kicked off when querying the URL in that way. The weird thing is that when I query it using a Ruby script from the same machine, it works just fine.
  • I have to do the timeout because if I just open the window then immediately close it, the browser does what it is supposed to, but it's too quick for the Hudson server to register it and start the job.
  • I have tried putting other statements besides trigger.close(); inside the anonymous function, and they are not executed either. There is no question that setTimeout is not executing the block it is supposed to be.

Thank you for any help you may be able to give me. I have been toying with this for hours and cannot figure out why my code is not doing the timeout right.

figured out this problem in the course of doing something else, so I thought I'd share the solution in case anyone else has the same problem. The issue was that I was calling this function using the onClick attribute of a submit button in a form. When the form is submitted it calls the function, and then the page is immediately reloaded after the function executes, which cancels the timeout that was set in the triggerJob function. You must use a link, radio button, etc. if you want to use setTimeout in this manner. Thanks for everyone who tried to help me.

Drew

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