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

javascript - How to execute the function once? - Stack Overflow

programmeradmin1浏览0评论
$("#div1, #div2").fadeIn('500',function(){
    {
        console.log('Test');
    }
});

Fiddle here: /

The above code will print 'Test' two times in the console. How can I make it print only one time. Is it possible?

$("#div1, #div2").fadeIn('500',function(){
    {
        console.log('Test');
    }
});

Fiddle here: http://jsfiddle.net/y97h9/

The above code will print 'Test' two times in the console. How can I make it print only one time. Is it possible?

Share Improve this question asked Apr 8, 2013 at 14:52 user2257938user2257938 6
  • What do you except? if div2 not exists? Test or no Test in console? – Grim Commented Apr 8, 2013 at 14:54
  • put a boolean outside the check, switch it inside the check. – Shark Commented Apr 8, 2013 at 14:54
  • 5 You've called the function on 2 different DOM elements. It's normal that the function gets called twice. What else did you expect to happen? – Darin Dimitrov Commented Apr 8, 2013 at 14:54
  • possible duplicate of Callback of .animate() gets called twice jquery (the unmarked answer is the one you're looking for) – Kevin B Commented Apr 8, 2013 at 14:54
  • The first parameter for fadeIn needs to be a String ("slow" or "fast") or a Number (representing the milliseconds the animation should take to complete). Passing "500" will just use the default 400 milliseconds since it's a String. – Ian Commented Apr 8, 2013 at 15:05
 |  Show 1 more comment

3 Answers 3

Reset to default 27

Sure, you can use jQuery promise to solve multiple callbacks problem:

$("#div1, #div2").fadeIn('500').promise().done(function()
{
    console.log('Test');
});

The .promise() method returns a dynamically generated Promise that is resolved once all actions of a certain type bound to the collection, queued or not, have ended

Working Demo

The callback will run once for every matched element. You can always set a flag to see if it's been run already though:

var hasRun = false;
$("#div1, #div2").fadeIn('500', function() {
    if (hasRun) return;
    console.log('Test');
    hasRun = true;
});

Use a boolean flag to prevent console.log('Test'); from being called twice.

var isCalled = false;
$("#div1, #div2").fadeIn('500',function(){
    if(!isCalled) {
        isCalled = true;
        console.log('Test');
    }
});
发布评论

评论列表(0)

  1. 暂无评论