首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >延迟吞吐-监视执行

延迟吞吐-监视执行
EN

Stack Overflow用户
提问于 2015-07-31 16:42:28
回答 3查看 2.1K关注 0票数 1

我正在使用gulp-watch监视文件更改,我的代码如下所示:

代码语言:javascript
复制
watch('public/**/*.js',function(){
    runSequence('compressjs','browser-sync','jshint');
});

它工作得很好。但是,因为它每次都会在文件发生更改时运行任务,所以当有多个文件发生更改时,它会导致重复执行任务。

如何延迟任务的执行,以便在极短的时间内有1个以上的文件更改时,它只执行任务一次,并且只在最后一个文件更改完成后执行?

EN

回答 3

Stack Overflow用户

发布于 2015-07-31 16:53:47

摘自:https://remysharp.com/2010/07/21/throttling-function-calls#comment-216435

试试这个:

代码语言:javascript
复制
function debounce(fn, delay) {
  var timer = null;
  return function () {
    var context = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };
}

watch('public/**/*.js',function(){
    debounce(runSequence('compressjs','browser-sync','jshint'), 500);
});
票数 3
EN

Stack Overflow用户

发布于 2018-09-16 00:41:51

在Gulp 4中,gulp.watch支持设置延迟。有关完整的细节,请参阅my answer here

票数 2
EN

Stack Overflow用户

发布于 2017-03-22 21:45:51

经过多次搜索和多次失败后,我想出了一个简单的解决方案,其中我的函数'buildAngularApp‘相当于'runSequence’。以下是代码示例:

代码语言:javascript
复制
//the files to watch    
var backendModules = ['**/*.min.js']
var delay = 2000;

/*
The watched build task
*/
gulp.task('watchBuild', function () { 
    console.log('Watching: ' + backendModules);
    gulp.watch(backendModules,
        function () {
            setTimeout(function () {
                console.log('Timer ' + delay + ' Reached');
                return buildAngularApp();
            }, delay);
        });
});

/*
The non watched task to build. calls the same build function
*/
gulp.task('build', function () {
    return buildAngularApp();
})

/*
The gulp task wrapped in a function
*/
function buildAngularApp() {
    return gulp.src(backendModules)
        .pipe($.useref())
        .pipe($.sourcemaps.init())
        .pipe($.concat('app.js'))
        .pipe($.sourcemaps.write('.'))
        .pipe(gulp.dest('lib/js'))
        .pipe($.size({
            title: path.join('lib/js'),
            showFiles: true
        }));
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31741797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档