开发者

how to call javascript methods sequentially on onclick event

I need to call two functions sequentially (means one by one) in javascript on onclick event.

The requirement is to get the data from the backend and then make the cell highlight. Below code snippet is used for this:

cell1.onclick=function() {
    getData("FileName");
    setTimeout("setHighlight('F开发者_JS百科ileName')", 500);
};

Currently i am using the setTimeout for calling the second method after a delay of 500ms.

The problem with above code is if getData method takes more than 500ms to get the data from backend then in that case cell would not get highlighted.

Is there any way to do this?

Thanks Jyoti


To get data from the backend, you probably are using AJAX.

And in the callback function you are populating the data. After this step, call the highlight function.

You probably have something like this:

      xmlHttp.onreadystatechange = function() 
      { 
         if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
         { 
            // do something with the response here
            highlightData();  //<---- the function to highlight data
         } 
      } 


You should add another parameter to getData, which is a function to execute when you have the data. So,

function getData(filename, callback) {
  // get the data
  // when you have the data, do callback(filename);
}

then you can do

getData("FileName", setHighlight);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜