我正在使用gulp-watch监视文件更改,我的代码如下所示:
watch('public/**/*.js',function(){
runSequence('compressjs','browser-sync','jshint');
});它工作得很好。但是,因为它每次都会在文件发生更改时运行任务,所以当有多个文件发生更改时,它会导致重复执行任务。
如何延迟任务的执行,以便在极短的时间内有1个以上的文件更改时,它只执行任务一次,并且只在最后一个文件更改完成后执行?
发布于 2015-07-31 16:53:47
摘自:https://remysharp.com/2010/07/21/throttling-function-calls#comment-216435
试试这个:
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);
});发布于 2018-09-16 00:41:51
在Gulp 4中,gulp.watch支持设置延迟。有关完整的细节,请参阅my answer here。
发布于 2017-03-22 21:45:51
经过多次搜索和多次失败后,我想出了一个简单的解决方案,其中我的函数'buildAngularApp‘相当于'runSequence’。以下是代码示例:
//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
}));
}https://stackoverflow.com/questions/31741797
复制相似问题