0

I use the code below to debounce the execution of the selector saveCurrentDocument.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    if (debounceTimer != NULL) {
        [debounceTimer invalidate];
        debounceTimer = NULL;
    }

    debounceTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self  selector:@selector(saveCurrentDocument) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:debounceTimer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
});

Currently, I noticed that dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) is creating another thread everytime an user types a letter in the app, so I tried to change it to this:

if (debounceQueue == nil) {
    debounceQueue = dispatch_queue_create("com.testing.SaveQueue", NULL);
}

dispatch_async(debounceQueue, ^{
    if (debounceTimer != NULL) {
        [debounceTimer invalidate];
        debounceTimer = NULL;
    }

    debounceTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self  selector:@selector(saveCurrentDocument) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:debounceTimer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
});

But now [debounceTimer invalidate] doesn't work anymore, and it's calling saveCurrentDocument every time.

Can anyone explain to me why this is happening?

Paulo Cesar
  • 2,250
  • 1
  • 25
  • 35

1 Answers1

0

It looks like you are adding the timer to the runloop twice. You should either remove the addTimer and run lines after instantiating debounceTimer, or alternatively you can use timerWithTimeInterval… instead of scheduledTimerWithTimeInterval…

mikepj
  • 1,256
  • 11
  • 11
  • Thanks for noticing that, fixed here. But I still have the same problem, invalidate doesn't work when using a DISPATCH_QUEUE_SERIAL on dispatch_queue_create – Paulo Cesar May 19 '16 at 19:16
  • This might help: http://stackoverflow.com/questions/10522928/run-repeating-nstimer-with-gcd – mikepj May 19 '16 at 19:25