最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - how to call javascript methods sequentially on onclick event - Stack Overflow

programmeradmin1浏览0评论

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('FileName')", 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

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('FileName')", 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

Share Improve this question edited Oct 20, 2010 at 10:19 Alberto Zaccagni 31.6k11 gold badges75 silver badges107 bronze badges asked Oct 20, 2010 at 10:16 JyotiJyoti 2,1153 gold badges27 silver badges30 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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)

  1. 暂无评论